为什么没有List.skip和List.take? [英] Why there is no List.skip and List.take?

查看:256
本文介绍了为什么没有List.skip和List.take?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么没有List.skip和List.take?当然有Seq.take和Seq.skip,但是它们不会创建列表.

一种可能的解决方案是:mylist |> Seq.skip N |> Seq.toList 但这会创建第一个枚举器,然后从该枚举器创建一个新列表.我认为可以有更直接的方法从不可变列表创建不可变列表.由于内部没有元素的复制,因此只有从新列表到原始列表的引用.

其他可能的解决方案(无抛出异常)是:

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

但这仍然不能回答问题...

解决方案

可能的List.skip 1称为List.tail,您可以tail进入列表 n 次. /p>

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

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...

解决方案

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.

这篇关于为什么没有List.skip和List.take?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆