Skip to content

Instantly share code, notes, and snippets.

@traiansf traiansf/unfold.hs
Created Feb 21, 2019

Embed
What would you like to do?
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
You can’t perform that action at this time.