为什么没有List.skip和List.take?
为什么没有List.skip和List.take?当然有 Seq.take 和 Seq.skip,但它们不会因此创建列表。
一种可能的解决方案是: mylist |> Seq.skip N |>顺序排列 但这会创建第一个枚举器,然后从该枚举器创建一个新列表。我认为可能有更直接的方法从不可变列表创建不可变列表。由于内部没有元素的复制,因此只有从新列表到原始列表的引用。
其他可能的解决方案(不引发异常)是:
let rec listSkip n xs =
match (n, xs) with
| 0, _ -> xs
| _, [] -> []
| n, _::xs -> listSkip (n-1) xs
但这仍然没有回答问题......
Why there is no List.skip and List.take? There is of course Seq.take and Seq.skip, but they does not create lists as a result.
One possible solution is: mylist |> Seq.skip N |> Seq.toList
But this creates first enumerator then a new list from that enumerator. I think there could be more direct way to create a immutable list from immutable list. Since there is no copying of elements internally there are just references from the new list to the original one.
Other possible solution (without throwing exceptions) is:
let rec listSkip n xs =
match (n, xs) with
| 0, _ -> xs
| _, [] -> []
| n, _::xs -> listSkip (n-1) xs
But this still not answer the question...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
顺便说一句,您可以将函数添加到列表模块中:
BTW, you can add your functions to List module:
可能的
List.skip 1
称为List.tail
,您可以将tail
放入列表 n次。无论如何,List.take 都必须创建一个新列表,因为只能共享不可变列表的常见后缀。
The would-be
List.skip 1
is calledList.tail
, you can justtail
into the list n times.List.take
would have to create a new list anyway, since only common suffixes of an immutable list can be shared.