Created
February 21, 2019 08:51
-
-
Save traiansf/bef128b424061fbf1e723fcb6e642f33 to your computer and use it in GitHub Desktop.
unfoldr, unfoldl, and a simple example
This file contains 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
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