Problem 7
(**) Flatten a nested list structure.
Transform a list, possibly holding lists as elements into a `flat’ list by replacing each list with its elements (recursively).
Example:
* (my-flatten '(a (b (c d) e)))
(A B C D E)
Example in Haskell:
We have to define a new data type, because lists in Haskell are homogeneous.
data NestedList a = Elem a | List [ NestedList a]
* Main> flatten ( Elem 5 )
[ 5 ]
* Main> flatten ( List [ Elem 1 , List [ Elem 2 , List [ Elem 3 , Elem 4 ] , Elem 5 ] ] )
[ 1 , 2 , 3 , 4 , 5 ]
* Main> flatten ( List [ ] )
[ ]
Solution:
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
data NestedList a = Elem a | List [NestedList a]
deriving Show
flatten :: NestedList a -> [a]
flatten (Elem x) = [x]
flatten (List []) = []
--flatten (List [Elem x]) = [x]
flatten (List (x:xs)) = flatten x ++ flatten (List xs)
-- let toflat = List [Elem 1, List [Elem 2, List [Elem 3, Elem 4], Elem 5]]
View the code on Gist .