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?
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.
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.
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]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With