Skip to content
Discussions/App Development/Flatten a listForum ↗

Flatten a list

App Development8 posts559 views13 likesLast activity May 2020
ME
meetOP
May 2020

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]

ME
meet
May 2020

Just realised I could achieve what I want using concat:
concat [ concat [ [111,112], [121,122] ], concat[ [211,212], [221,222] ] ]

CO
cocreature
May 2020

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]]])
ME
meet
May 2020

Beautiful :’)
Thanks!

GE
georg
May 2020

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.

ME
meet
May 2020
georg:

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.

Thank you @georg - concatMap is a recently discovered joy!

SA
SamirTalwar
May 2020

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.

← Back to Discussions