Created
September 3, 2020 15:02
-
-
Save robrix/2f6daf22f1b3cd4ea9e051a02dd13f3e to your computer and use it in GitHub Desktop.
Mendler-style iteration in Haskell
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
{-# 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