Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cut inner lists to equal length in Haskell

Tags:

list

haskell

Let's say we have a list of lists, and we want to cut all inner lists down to the length of the shortest inner list -- for instance, from [[1,2,3,4],[2,3],[3,9]] we should get [[1,2],[2,3],[3,9]].

This is my code up to now (it doesn't work):

cut :: [[a]] -> [[a]]
cut = map (\xs -> drop ((min(length xs)) - length xs) xs)

I tried to solve it like this: There has to be a function that returns the length of the shortest list and, with that, we need a further function that cuts all the lists from the beginning to this new length. But, in fact, I don't have a clue.

like image 920
Janik Ti Avatar asked Dec 07 '22 15:12

Janik Ti


1 Answers

Is it what you want ?

truncateList :: [[a]] -> [[a]]
truncateList list = map (\x -> take l x) list
  where
  l = minimum (map length list)

or, shorter,

truncateList :: [[a]] -> [[a]]
truncateList list = map (take l) list
  where
  l = minimum (map length list)
like image 146
Stéphane Laurent Avatar answered Jan 04 '23 15:01

Stéphane Laurent