What’s the best way to “flatten” embedded lists… Say, [[[a]]] -> [a]
?
So for example:
flatten [ [ [111,112], [121,122] ], [ [211,212], [221,222] ] ] == [111,112,121,122,211,212,221,222]
2 Likes
Just realised I could achieve what I want using concat
:
concat [ concat [ [111,112], [121,122] ], concat[ [211,212], [221,222] ] ]
1 Like
You don’t need to call concat
separately for each element of the inner list. You can just chain calls to concat
depending on how many levels you want to flatten, e.g.,
concat (concat [[[111,112], [121,122]], [[211,212], [221,222]]])
3 Likes
Beautiful :’)
Thanks!
2 Likes
1 Like
Honorable mention also for concatMap
which is handy if you map over a function that returns a list, and want to concatenate the resulting lists all in one go. It’s the equivalent to SelectMany
in LINQ for example.
2 Likes
Thank you @georg - concatMap
is a recently discovered joy!
DAML being a Haskell dialect, you can also use >>=
.
[1, 2, 3] >>= (\x -> [x, x * 2]) == [1, 2, 2, 4, 3, 6]
Sometimes binding is easier to read, sometimes concatMap
is.
2 Likes