为什么 Seq.groupBy 不能像我认为的那样与列表一起工作? (F#)

Why doesn't Seq.groupBy work like I think it will with lists? (F#)

这是一个示例代码:

let x = [5, 6, 65, 2, 3];
let p = x.Head;
let y = Seq.groupBy (fun xx -> if xx < p then -1 elif xx > p then 1 else 0) x
printfn "%A" y

我预计它会输出

[(0, [5]), (1, [6, 65]), (-1, [2, 3])]

但实际上它输出

seq [(0, seq [(5, 6, 65, 2, 3)])]

我误会了什么?

问题是您的列表是一个包含单个元组的列表:

let x = [5, 6, 65, 2, 3];

这是因为逗号定义了一个元组。这实际上与写作相同:

// Build a tuple
let temp = (5,6,65,2,3)
// Make a list where the single item is the tuple
let x = [temp]

您需要使用分号来定义列表的元素:

let x = [5; 6; 65; 2; 3];

如果您进行更改,您将看到:

seq [(0, seq [5]); (1, seq [6; 65]); (-1, seq [2; 3])]