简体   繁体   中英

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?

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 ab 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"]

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 .

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 (~-)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM