Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Operations on list of lists

Tags:

list

f#

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?

like image 863
Worice Avatar asked Nov 21 '16 19:11

Worice


People also ask

Can you have a list of list of lists in Python?

Python provides an option of creating a list within a list. If put simply, it is a nested list but with one or more lists inside as an element. Here, [a,b], [c,d], and [e,f] are separate lists which are passed as elements to make a new list. This is a list of lists.

What is the use of (*) operator in list?

Repetition Operator(*) on List Items. Python List also includes the * operator, which allows you to create a new list with the elements repeated the specified number of times.


1 Answers

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]]
like image 133
Mark Seemann Avatar answered Oct 30 '22 23:10

Mark Seemann