Skip to content

Instantly share code, notes, and snippets.

@emonkak
Created July 29, 2011 01:43
Show Gist options
  • Save emonkak/1112968 to your computer and use it in GitHub Desktop.
Save emonkak/1112968 to your computer and use it in GitHub Desktop.
UnNesting.hs
data Item a = Atom a
| List [Item a]
deriving (Eq, Show)
flatten :: Item a -> [a]
flatten (Atom x) = [x]
flatten (List xs) = concat $ map flatten xs
flatten' :: Item a -> [a]
flatten' (Atom x) = [x]
flatten' (List xs) = helper [] (reverse xs)
where
helper acc [] = acc
helper acc (Atom x:xs) = helper (x:acc) xs
helper acc (List xs':xs) = helper (helper acc (reverse xs')) xs
main = print $ flatten $
List [ Atom 'a'
, List [ Atom 'b'
, Atom 'c']
, Atom 'd'
, Atom 'e'
, List [ Atom 'f'
, Atom 'g'
, List [ Atom 'h'
, Atom 'i'
, Atom 'j' ]
, List [ Atom 'k' ]
, List [ Atom 'l'
, List [ Atom 'm'
, Atom 'n'] ]
, Atom 'o' ]
, Atom 'p'
, Atom 'q' ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment