List List Operations

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?

+4
source share
1 answer

You can implement a function like

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

or

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

depending on how you want it to work if there isn’t enough 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]]
+8
source

Source: https://habr.com/ru/post/1661502/


All Articles