为什么没有List.skip和List.take?

发布于 2024-10-05 09:34:45 字数 411 浏览 2 评论 0原文

为什么没有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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

安静 2024-10-12 09:34:45

顺便说一句,您可以将函数添加到列表模块中:

module List =
   let rec skip n xs = 
      match (n, xs) with
      | 0, _ -> xs
      | _, [] -> []
      | n, _::xs -> skip (n-1) xs

BTW, you can add your functions to List module:

module List =
   let rec skip n xs = 
      match (n, xs) with
      | 0, _ -> xs
      | _, [] -> []
      | n, _::xs -> skip (n-1) xs
夜司空 2024-10-12 09:34:45

可能的 List.skip 1 称为 List.tail,您可以将 tail 放入列表 n次。

无论如何,List.take 都必须创建一个新列表,因为只能共享不可变列表的常见后缀。

The would-be List.skip 1 is called List.tail, you can just tail 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文