Created
May 17, 2021 18:38
-
-
Save snowleopard/4e6eb6c20a4ead1a17bb71ffa2b3f6ff to your computer and use it in GitHub Desktop.
Generalised unfoldr
This file contains hidden or 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
-- See http://www.staff.city.ac.uk/~ross/papers/FingerTree.html | |
class Monoid m => Measured a m where | |
measure :: a -> m | |
instance Measured a [a] where | |
measure a = [a] | |
-- Generalised to any resulting monoid from `unfoldr :: (b -> Maybe (a, b)) -> b -> [a]` | |
unfoldr :: Measured a m => (b -> Maybe (a, b)) -> b -> m | |
unfoldr f b = case f b of | |
Nothing -> mempty | |
Just (a, b) -> measure a <> unfoldr f b | |
-- This definition remains unchanged compared to the one based on the standard `unfoldr` | |
iterate :: (a -> a) -> a -> [a] | |
iterate f = unfoldr (\a -> Just (a, f a)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment