Reputation: 1248
List.Sort
sorts a list from low to high - How does one sort from high to low? Is there some kind of library function for this?
Upvotes: 3
Views: 2298
Reputation: 14468
You can use List.sortBy
to sort by a custom function, and use the unary minus operator ~-
as such function in a compact notation:
let list = [1..10]
list |> List.sortBy (~-)
Upvotes: 1
Reputation: 41290
If you looked at the linked thread F# Seq.sortBy in descending order, there is a chance of overflow when you use List.sortBy (fun x -> -x)
. To be correct, it should be:
List.sortBy (fun x -> -x-1)
In F# 4.0 (that comes with Visual Studio 2015 Preview), there are sortDescending/sortByDescending
functions for this exact purpose.
You can use
list
|> List.sortDescending
or
list
|> List.sortByDescending id
See the comprehensive list of new core library functions at https://github.com/fsharp/FSharpLangDesign/blob/master/FSharp-4.0/ListSeqArrayAdditions.md.
Upvotes: 5
Reputation: 17651
For a list of numbers:
list
|> List.sortBy (fun x -> -x)
The function (fun x -> -x)
negates the number, therefore reversing the order.
For comparables in general, use List.sortWith
with compare
. Observe the ordering of a b
in compare
:
> List.sortWith (fun a b -> compare a b) ["a";"s";"d";"f"];;
val it : string list = ["a"; "d"; "f"; "s"]
> List.sortWith (fun a b -> compare b a) ["a";"s";"d";"f"];;
val it : string list = ["s"; "f"; "d"; "a"]
Upvotes: 7