F#:InvalidOperationException:输入序列的元素数量不足?

标签 f# sequences invalidoperationexception skip empty-list

我有一个返回记录序列的函数。在该函数中,我使用空白的虚拟记录开始列表构建(可能有更好的方法),因为我需要积累相似的记录,所以我用空白记录“启动泵”。这是我的代码:

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/

相关文章:

f# - 在 F# 中将 float 转换为字符串?

k个元素的计数序列

algorithm - 子序列的概率计算和算法

clojure - 获取惰性列表的前 n 项的惰性列表

C# 找出导致 Sql 异常的列

c++ - 调用vector.erase()函数时出现无效指针操作错误

python - 在 Deedle 中使用默认值将列添加到数据框

f# - 使用 Accord.net 获取数据点到其质心的距离

recursion - 为什么包含 Console.ReadLine() 的函数不完整?

c# - 将节点添加到 TreeView 会导致 Thread-Exception