RosettaCodeData/Task/Flatten-a-list/Haskell/flatten-a-list-3.hs

30 lines
701 B
Haskell
Raw Permalink Normal View History

2017-09-23 10:01:46 +02:00
data NestedList a
= NList [NestedList a]
| Entry a
2013-04-10 21:29:02 -07:00
flatten :: NestedList a -> [a]
2017-09-23 10:01:46 +02:00
flatten nl = flatten_ nl []
2013-04-10 21:29:02 -07:00
where
2017-09-23 10:01:46 +02:00
flatten_ :: NestedList a -> [a] -> [a]
flatten_ (Entry a) cont = a : cont
flatten_ (NList entries) cont = foldr flatten_ cont entries
2013-04-10 21:29:02 -07:00
2017-09-23 10:01:46 +02:00
-- By passing through a list to which the results will be prepended,
-- we allow for efficient lazy evaluation
2013-04-10 21:29:02 -07:00
example :: NestedList Int
2017-09-23 10:01:46 +02:00
example =
NList
[ NList [Entry 1]
, Entry 2
, NList [NList [Entry 3, Entry 4], Entry 5]
, NList [NList [NList []]]
, NList [NList [NList [Entry 6]]]
, Entry 7
, Entry 8
, NList []
]
2013-04-10 21:29:02 -07:00
main :: IO ()
main = print $ flatten example
-- output [1,2,3,4,5,6,7,8]