Skip to content
CCPEDIAby Unity Nodes
Discussions/App Development/Flatten a listForum ↗

Flatten a list

App Development8 posts581 views13 likesLast activity May 2020
ME
meetOP
May 2020 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]

ME
meet
May 2020 1

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 3

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 2

Beautiful :’)
Thanks!

GE
georg
May 2020 2

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 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 concatMap is.

← Back to Discussions