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

2020-08-10 07:31发布

问题:

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

回答1:

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.



回答2:

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