开发者

Why there is no List.skip and List.take?

开发者 https://www.devze.com 2023-01-29 00:04 出处:网络
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.

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 -&开发者_开发技巧gt; listSkip (n-1) xs

But this still not answer the question...


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消