Flatten a list
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]
Just realised I could achieve what I want using concat:
concat [ concat [ [111,112], [121,122] ], concat[ [211,212], [221,222] ] ]
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]]])
Beautiful :’)
Thanks!
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.
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 - 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.