Created
July 29, 2011 01:43
-
-
Save emonkak/1112968 to your computer and use it in GitHub Desktop.
UnNesting.hs
This file contains 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 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