Flatten a list
- meetOP 2
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] - meet 1
Just realised I could achieve what I want using
concat:
concat [ concat [ [111,112], [121,122] ], concat[ [211,212], [221,222] ] ] - cocreature 3
You don’t need to call
concatseparately for each element of the inner list. You can just chain calls toconcatdepending on how many levels you want to flatten, e.g.,concat (concat [[[111,112], [121,122]], [[211,212], [221,222]]]) - meet 2
Beautiful :’)
Thanks! - georg 2
Honorable mention also for
concatMapwhich 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 toSelectManyin LINQ for example. - meet
georg:Honorable mention also for
concatMapwhich 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 toSelectManyin LINQ for example.Thank you @georg -
concatMapis a recently discovered joy! - SamirTalwar 2
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
concatMapis.