Skip to content

Instantly share code, notes, and snippets.

@sukhodolin
Created April 3, 2014 00:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sukhodolin/9946125 to your computer and use it in GitHub Desktop.
Save sukhodolin/9946125 to your computer and use it in GitHub Desktop.
-- 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