Skip to content

Instantly share code, notes, and snippets.

@snowleopard
Created May 17, 2021 18:38
Show Gist options
  • Save snowleopard/4e6eb6c20a4ead1a17bb71ffa2b3f6ff to your computer and use it in GitHub Desktop.
Save snowleopard/4e6eb6c20a4ead1a17bb71ffa2b3f6ff to your computer and use it in GitHub Desktop.
Generalised unfoldr
-- 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