F#中的排序列表从高到低排序

Dr.*_*erg 2 sorting f#

List.Sort
Run Code Online (Sandbox Code Playgroud)

从低到高对列表进行排序 - 如何从高到低排序?这有什么样的库函数吗?

Min*_*ang 6

有关数字列表:

list
|> List.sortBy (fun x -> -x)
Run Code Online (Sandbox Code Playgroud)

该函数(fun x -> -x)否定了数字,因此颠倒了顺序.

对于一般可比,使用List.sortWith与compare.观察a bin 的顺序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"]
Run Code Online (Sandbox Code Playgroud)


pad*_*pad 5

如果您按降序查看链接的线程F#Seq.sortBy,则在使用时可能会溢出List.sortBy (fun x -> -x).为了正确,它应该是:

List.sortBy (fun x -> -x-1)
Run Code Online (Sandbox Code Playgroud)

在F#4.0(Visual Studio 2015 Preview附带)中,有一些sortDescending/sortByDescending用于此目的的函数.

您可以使用

list
|> List.sortDescending
Run Code Online (Sandbox Code Playgroud)

要么

list
|> List.sortByDescending id
Run Code Online (Sandbox Code Playgroud)

请参阅https://github.com/fsharp/FSharpLangDesign/blob/master/FSharp-4.0/ListSeqArrayAdditions.md上的新核心库函数的完整列表.