Skip to content

Instantly share code, notes, and snippets.

@robrix
Created September 3, 2020 15:02
Show Gist options
  • Save robrix/2f6daf22f1b3cd4ea9e051a02dd13f3e to your computer and use it in GitHub Desktop.
Save robrix/2f6daf22f1b3cd4ea9e051a02dd13f3e to your computer and use it in GitHub Desktop.
Mendler-style iteration in Haskell
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE RankNTypes #-}
module Mendler where
class Iter b t | t -> b where
iter :: (forall x . (x -> a) -> b x -> a) -> t -> a
data ListF a b = Nil | Cons a b
instance Iter (ListF a) [a] where
iter alg = go
where
go [] = alg go Nil
go (x:xs) = alg go (Cons x xs)
-- >>> iter (\ k x -> case x of { Nil -> [] ; Cons x xs -> x : k xs }) "abcd"
-- "abcd"
-- >>> iter (\ k x -> case x of { Nil -> [] ; Cons x xs -> k xs ++ [x] }) "abcd"
-- "dcba"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment