Skip to content

Instantly share code, notes, and snippets.

@traiansf
Created February 21, 2019 08:51
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 traiansf/bef128b424061fbf1e723fcb6e642f33 to your computer and use it in GitHub Desktop.
Save traiansf/bef128b424061fbf1e723fcb6e642f33 to your computer and use it in GitHub Desktop.
unfoldr, unfoldl, and a simple example
unfoldl :: (a -> Maybe (a, b)) -> a -> [b]
unfoldl f a = go a []
where
go a l = case f a of
Nothing -> l
Just (a, b) -> go a (b:l)
unfoldr :: (a -> Maybe (b, a)) -> a -> [b]
unfoldr f = go
where
go a = case f a of
Nothing -> []
Just (b, a) -> b:go a
natl :: Int -> Maybe (Int, Int)
natl x
| x <= 0 = Nothing
| otherwise = Just (x-1, x)
testl :: Bool
testl = unfoldl natl 10 == [1,2,3,4,5,6,7,8,9,10]
natr :: Int -> Maybe (Int, Int)
natr = fmap (\(x,y) -> (y,x)) . natl
testr :: Bool
testr = unfoldr natr 10 == [10,9,8,7,6,5,4,3,2,1]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment