Created
April 3, 2014 00:31
-
-
Save sukhodolin/9946125 to your computer and use it in GitHub Desktop.
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
-- One more solution for | |
-- http://www.haskell.org/haskellwiki/99_questions/Solutions/7 | |
-- that works for infinite input too (i.e. it's lazy in its input) | |
data NestedList a = Elem a | List [NestedList a] | |
get1st :: NestedList a -> (Maybe a, Maybe (NestedList a)) | |
get1st (Elem e) = (Just e, Nothing) | |
get1st (List []) = (Nothing, Nothing) | |
get1st (List (l : ls)) = let (e, l') = get1st l | |
tail = maybe (List ls) | |
(\h -> List (h : ls)) l' | |
in maybe (get1st tail) | |
(\e' -> (Just e', Just tail)) e | |
flatten :: NestedList a -> [a] | |
flatten nl = let (a1, as) = get1st nl | |
in maybe [] (: maybe [] flatten as) a1 | |
main = putStrLn . show . (take 10) . flatten $ | |
List $ map Elem [1..] | |
--List [List [List [], Elem 4], List [Elem 3, Elem 2], Elem 1] | |
--(List [] :: NestedList Int) | |
--(Elem 1) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment