I built a simple function that, given a list, returns the first nelements of this list.
let rec first l n =
match l, n with
(_, 0) -> l
| (x::xs 1) -> [x]
| (x::xs n) -> x::(first xs (n-1))
But what if input is a list of lists, not a list? I would like to create a function that, given a list of lists, returns the first nelements from each list. For instance:
first [[1; 2]; [5; 6; 7]; []; []; [9; 8; 0]] 1 =
[1; 5; 9]
I tried to figure out the approach by making the template a list of lists:
let rec first l n =
match l, n with
(_, 0) -> l
| ([[x]::[xs]], n) -> [x::[first xs (n-1)]]
It doesn't work, but I'm more concerned about the approach. Is it correct?
source
share