在 F# 中调用 Seq.skip 和 Seq.take
let aBunch = 1000 let offset = 0 let getIt offset = MyIEnumerable |> Seq.skip aBunch * offset |> Seq.take aBunch |> Seq.iter ( .. some processing ...)
使用不同的偏移量调用 getIt() 最终会给我一个“无效操作”异常,并附有“输入序列元素不足”的附加信息,
我试图理解为什么,因为 Seq.Skip 和 Seq.take 都不会根据情况生成异常到在线文档 FSharp Collections
版本:(Visual Studio 2010) Beta 1
let aBunch = 1000 let offset = 0 let getIt offset = MyIEnumerable |> Seq.skip aBunch * offset |> Seq.take aBunch |> Seq.iter ( .. some processing ...)
Calling getIt() with different offsets eventually gives me an 'Invalid operation' exception with additional info that 'the input sequence had insufficient elements'
I try to understand why, as both the Seq.Skip and Seq.take do not generate an exception according to the online documentation FSharp Collections
Version: (Visual Studio 2010) Beta 1
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
这是使用内置函数的稍短的“skipSafe”实现:
或者,如果您希望直接将其内联到当前管道中,请替换
为
Here's a slightly shorter "skipSafe" implementation using built in functions:
Or if you wish to just inline it into your current pipeline directly, replace
with
对于无异常的
skip
,您可以将自己的版本添加到 Seq 模块,如下所示:与
Seq.truncate
结合(这是无异常的Seq.take 等效 - 它将需要尽可能多的可用项目而不引发异常)。
For an exceptionless
skip
you can add your own version to the Seq module like this:Combined with
Seq.truncate
(which is an exceptionlessSeq.take
equivalent - it will take as much items are available without throwing an exception).我知道这是一个老问题,但如果有人像我一样在搜索中遇到这个问题:
您可以使用 Seq.truncate 如果您最多需要 n 个项目。 如果可用的项目少于 n 个,它不会抛出异常。
I know this is an old question, but in case someone comes across this in a search the way I did:
You can use Seq.truncate if you want at most n items. It won't throw an exception if fewer than n items are available.
如果使用大于序列的值调用,Seq.skip 和 Seq.take 都会抛出此异常。 你可以查看Seq.fs中的源代码来了解原因:
Both Seq.skip and Seq.take will throw this exception if called with a value larger than the sequence. You can check the source code in Seq.fs to see why:
对于
skip
,您可以通过委托给 LINQ 的Skip
轻松定义一个具有(大概)最佳性能的简单skipSafe
:对于
take
code>,正如其他答案所说,您可以只使用Seq.truncate
,或者可选地为其别名:For
skip
, you can easily define a trivialskipSafe
with (presumably) optimal performance by delegating to LINQ'sSkip
:For
take
, as the other answers say, you can just useSeq.truncate
, or optionally alias it: