Dr. John A Zoidberg
Dr. John A Zoidberg

Reputation: 1248

Sort list High-to-Low in F#

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

Answers (3)

Mau
Mau

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

pad
pad

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

Ming-Tang
Ming-Tang

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

Related Questions