Flatten a list: Difference between revisions

Content added Content deleted
Line 1,710: Line 1,710:
= Leaf a
= Leaf a
| Node [Tree a]
| Node [Tree a]

flatten :: Tree a -> [a]
flatten :: Tree a -> [a]
flatten (Leaf x) = [x]
flatten (Leaf x) = [x]
flatten (Node xs) = concatMap flatten xs
flatten (Node xs) = xs >>= flatten

main :: IO ()
main :: IO ()
main =
main =
Line 1,728: Line 1,728:
, Node []
, Node []
]
]
-- output: [1,2,3,4,5,6,7,8]</lang>
-- [1,2,3,4,5,6,7,8]</lang>


Yet another choice, custom data structure, efficient lazy flattening:
Yet another choice, custom data structure, efficient lazy flattening: