Sorting By Functions in F#
Our example demonstrates how to implement custom sorting in F#. We’ll sort strings by their length and custom objects by a specific field.
To run the program, save it as sorting_by_functions.fsx
and use the F# interactive or compile and run it:
In this F# version:
We define a
Person
record type to represent our custom object.The
lenCmp
function is defined to compare string lengths, similar to the Go version.We use
List.sortWith
instead ofslices.SortFunc
. This function takes a comparison function and a list, and returns a new sorted list.For sorting the list of
Person
records, we use an inline comparison function withList.sortWith
.The
printfn
function is used for output, which is similar tofmt.Println
in Go.
Note that F# lists are immutable, so List.sortWith
returns a new sorted list rather than modifying the original list in place. This is a key difference from the Go version, which modifies the slice in place.
Also, F# has built-in support for records, which we use instead of Go’s struct type. This makes our Person
type more idiomatic to F#.