Worice
Worice

Reputation: 4047

Operations on list of lists

I built a simple function that, given a list, returns the first n elements of that 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 the input is a list of lists, rather than a list? I would like to build a function that, given a list of lists, returns the first n elements from every list. For example:

first [[1; 2]; [5; 6; 7]; []; []; [9; 8; 0]] 1 = 
[1; 5; 9]

I tried to figure out an approach, by making the pattern a list of lists:

let rec first l n =
    match l, n with
    (_, 0) -> l
    | ([[x]::[xs]],  n) -> [x::[first xs (n-1)]]

It does not work, but I am more concerned about the approach. Is it correct?

Upvotes: 5

Views: 628

Answers (1)

Mark Seemann
Mark Seemann

Reputation: 233505

You can implement such a function as

let firsts i = List.map (List.truncate i)

or

let firsts' i = List.map (List.take i)

depending on how you'd like it to behave if there are insufficient numbers of elements in one of the lists.

> firsts 2 [[1..10]; [11..20]; [21..30]];;
val it : int list list = [[1; 2]; [11; 12]; [21; 22]]

Upvotes: 8

Related Questions