我有一个返回记录序列的函数。在该函数中,我使用空白的虚拟记录开始列表构建(可能有更好的方法),因为我需要积累相似的记录,所以我用空白记录“启动泵”。这是我的代码:
let consolidate(somethings:seq<Something>) =
let mutable results = ResizeArray()
let mutable accumulatedSomething = {Foo = ""; Bar = ""; Count = 0;}
for s in somethings do
if s.Foo = accumulatedSomething.Foo && s.Bar = accumulatedSomething.Bar then
accumulatedSomething <- {Foo = s.Foo; Bar = s.Bar;
Count = s.Count + accumulatedSomething.Count}
else
results.Add(accumulatedSomething)
accumulatedSomething <- e
results |> Seq.cast |> Seq.skip 1
如果你有办法让这个变得更好,我会洗耳恭听(我仍在程序上思考),但我仍然对这个具体问题的答案感兴趣。后来在我的代码中,我尝试打印出列表:
somethings |> Seq.iter( fun s -> printfn "%A" s)
当列表中有内容时,这可以正常工作。但是,如果列表为空,并且列表中的唯一记录是跳过的空白起始记录,则此行会失败,并出现 InvalidOperationException
并显示消息 The inputequence has an invalid number of of元素?
为什么会发生这种情况以及如何解决它?
最佳答案
当 somethings
为空列表时,就会出现问题。
在这种情况下,results
为空,并且在空列表上调用 Seq.skip 1
失败并出现错误。
我认为一个优雅的解决方案是将最后一行更改为
match results.Length with
| 0 -> results |> Seq.cast
| _ -> results |> Seq.cast |> Seq.skip 1
关于F#:InvalidOperationException:输入序列的元素数量不足?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17246001/