Sorting in F#
Our example demonstrates sorting in F#. We’ll look at sorting for built-in types first.
open System
// Sorting functions work for any comparable type in F#.
let strs = ["c"; "a"; "b"]
let sortedStrs = List.sort strs
printfn "Strings: %A" sortedStrs
// An example of sorting integers.
let ints = [7; 2; 4]
let sortedInts = List.sort ints
printfn "Ints: %A" sortedInts
// We can also check if a list is already in sorted order.
let isSorted = List.sort ints = ints
printfn "Sorted: %b" isSorted
To run the program, save it as sorting.fsx
and use the F# interactive or compile and run it as an executable.
$ dotnet fsi sorting.fsx
Strings: ["a"; "b"; "c"]
Ints: [2; 4; 7]
Sorted: true
In F#, the List.sort
function is used to sort lists. It works with any type that implements comparison, which includes all built-in types like strings and integers.
Unlike the Go example which modifies the original slice, F# creates a new sorted list. This is because F# emphasizes immutability.
The List.sort
function returns a new sorted list, leaving the original list unchanged. This is a key difference between F# (and functional programming in general) and imperative languages like Go.
To check if a list is sorted, we can compare the original list with its sorted version. If they’re equal, the original list was already sorted.
F# doesn’t have a built-in IsSorted
function like Go’s slices.IsSorted
, but we can easily implement this functionality as shown in the example.