Skip to content

Instantly share code, notes, and snippets.

@newmen
Last active December 27, 2015 21:59
Show Gist options
  • Save newmen/87199b3d1708aaaa825d to your computer and use it in GitHub Desktop.
Save newmen/87199b3d1708aaaa825d to your computer and use it in GitHub Desktop.
Pattern matching forever!
app_head :: [a] -> [a] -> [a]
app_head acc [] = acc -- so easy
app_head acc xs = acc ++ [head xs]
safe_heads :: [[a]] -> [a]
safe_heads [] = []
safe_heads xs = foldl app_head [] xs
-- hard way over Maybe
head' :: [a] -> Maybe a
head' [] = Nothing
head' (x:_) = Just x
tail' :: [a] -> Maybe [a]
tail' [] = Nothing
tail' (_:xs) = Just xs
app_head' :: [a] -> [a] -> [a]
app_head' acc xs = acc ++ maybe_next
where
maybe_item = head' xs
maybe_next = case maybe_item of
Nothing -> []
Just x -> [x]
safe_heads' :: [[a]] -> [a]
safe_heads' [] = []
safe_heads' xs = foldl app_head' [] xs
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment