Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

list

f#

sequences

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

like image 567
The_Ghost Avatar asked Dec 02 '10 10:12

The_Ghost


2 Answers

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
like image 137
vpolozov Avatar answered Oct 08 '22 04:10

vpolozov


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.

like image 44
Brian Avatar answered Oct 08 '22 04:10

Brian