F#Seq.sortBy降序排列 [英] F# Seq.sortBy in descending order
本文介绍了F#Seq.sortBy降序排列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我对F#还是很陌生,它来自Seq.sortBy函数,但是它以升序对列表进行排序.如何使用Seq.sort对其进行降序排序?
I am fairly new to F# and came by the Seq.sortBy function however it is sorting my list in ascending order. How do I get it to sort in descending order using the Seq.sort?
例如,示例代码为...
For instance an example code would be...
let DisplayList =
seq{0..10}
|> Seq.sortBy(fun x -> x)
|> Seq.iter(fun x -> Console.WriteLine(x.ToString()))
当我真的希望它从10变为1时,输出为1 2 3 4 5 6 7 8 9 10.
gives me an output of 1 2 3 4 5 6 7 8 9 10, when I really want it to do it from 10 to 1.
推荐答案
请注意其他答案,请注意一元减号和MININT:
Looking at the other answers, beware unary minus and MININT:
let a = [| 1; -1; System.Int32.MinValue; 0; System.Int32.MaxValue; 1 |]
printfn "%A" (a |> Array.sortBy (fun x -> x))
// [|-2147483648; -1; 0; 1; 1; 2147483647|]
printfn "%A" (a |> Array.sortBy (fun x -> -x)) // uh-oh!
// [|-2147483648; 2147483647; 1; 1; 0; -1|]
我认为您实际上想要的是负x减一:
I think you actually want negative-x-minus-one:
printfn "%A" (a |> Array.sortBy (fun x -> -x - 1))
// [|2147483647; 1; 1; 0; -1; -2147483648|]
表示跨越-2^N..2^N-1
的环绕整数类型.
for a wraparound integer type that spans -2^N..2^N-1
.
这篇关于F#Seq.sortBy降序排列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文