Why there is no List.skip and List.take?
Asked Answered
E

2

14

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

Evelinaeveline answered 2/12, 2010 at 10:13 Comment(1)
List.skip wouldn't need to create a new list, but List.take would.Thereat
M
11

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.

Maw answered 2/12, 2010 at 16:41 Comment(0)
C
12

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
Cervin answered 2/12, 2010 at 13:47 Comment(1)
good answer, but negative values of n. this always returns an empty list instead of the same. alternative: let rec skip n xs = if 0<n && not (List.isEmpty xs) then skip (n-1) (List.tail xs) else xsDarrel
M
11

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.

Maw answered 2/12, 2010 at 16:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.