| title | recursion schemes | ||
|---|---|---|---|
| sub_title | ana, cata, para, what? | ||
| date | |||
| theme |
|
recursion schemes
(in practice)
data Term
= Var String
| Fun String Term
| App Term Term
| Num Integer
| Add Term Term
| Sub Term Term
| Mul Term Term
| Div Term Term-- 1 + 2
example0 = Add (Num 1) (Num 2)
-- (2 + x) - 42
example1 = Sub (Add (Num 2) (Var "x")) (Num 42)
-- λx.x + 1
example2 = Fun "x" (Add (Var "x") (Num 1))data Term
= Var String
| Fun String Term
| App Term Term
| Num Integer
| Add Term Term
| Sub Term Term
| Mul Term Term
| Div Term Termpretty :: Term -> String
pretty (Var x)
= x
pretty (Fun x t)
= "(λ" <> x <> "." <> pretty t <> ")"
pretty (App a b)
= "(" <> pretty a <> " " <> pretty b <> ")"
pretty (Num n)
= show n
pretty (Add a b)
= "(" <> pretty a <> " + " <> pretty b <> ")"
pretty (Sub a b)
= "(" <> pretty a <> " - " <> pretty b <> ")"
pretty (Mul a b)
= "(" <> pretty a <> " * " <> pretty b <> ")"
pretty (Div a b)
= "(" <> pretty a <> " / " <> pretty b <> ")"data Term
= Var String
| Fun String Term
| App Term Term
| Num Integer
| Add Term Term
| Sub Term Term
| Mul Term Term
| Div Term TermfreeVars :: Term -> Set String
freeVars (Var x)
= Set.singleton x
freeVars (Fun x t)
= Set.difference (freeVars t) (Set.singleton x)
freeVars (App a b)
= Set.union (freeVars a) (freeVars b)
freeVars (Num _)
= Set.empty
freeVars (Add a b)
= Set.union (freeVars a) (freeVars b)
freeVars (Sub a b)
= Set.union (freeVars a) (freeVars b)
freeVars (Mul a b)
= Set.union (freeVars a) (freeVars b)
freeVars (Div a b)
= Set.union (freeVars a) (freeVars b)Recursive data structures are everywhere!
DEMO: in Effekt source/Tree
data Term
= Var String
| Fun String Term
| App Term Term
| Num Integer
| Add Term Term
| Sub Term Term
| Mul Term Term
| Div Term TermfoldTerm :: (String -> a) -> (String -> a -> a)
-> (a -> a -> a) -> (Integer -> a) -> (a -> a -> a)
-> (a -> a -> a) -> (a -> a -> a) -> (a -> a -> a)
-> Term -> a -- UGH!
foldTerm var fun app num add sub mul div = go
where
go (Var x) = var x
go (Fun x t) = fun x (go t)
go (App a b) = app (go a) (go b)
go (Num n) = num n
go (Add a b) = add (go a) (go b)
go (Sub a b) = sub (go a) (go b)
go (Mul a b) = mul (go a) (go b)
go (Div a b) = div (go a) (go b)data Term
= Var String
| Fun String Term
| App Term Term
| Num Integer
| Add Term Term
| Sub Term Term
| Mul Term Term
| Div Term Termpretty :: Term -> String
pretty = foldTerm
id
(\x t -> "(λ" <> n <> "." <> t <> ")")
(\a b -> "(" <> a <> " " <> b <> ")")
show
(\a b -> "(" <> a <> " + " <> b <> ")")
(\a b -> "(" <> a <> " - " <> b <> ")")
(\a b -> "(" <> a <> " * " <> b <> ")")
(\a b -> "(" <> a <> " / " <> b <> ")")
-- slightly better, hard to read/maintain- hard to read & maintain
- high probability for mistakes
- no separation between how functions recurse and what they do
- else: annoying folding functions
- also: you can not annotate additional information!
fold & data & recursion
lst = 1 : (2 : (3 : (4 : []))) : --- foldr (+) 0 --> + ------------------> + ------ ... --> 10
/ \ / \ / \
1 : 1 + 1 +
/ \ / \ / \
2 : 2 + 2 +
/ \ / \ / \
3 : 3 + 3 4
/ \ / \
4 [] 4 0
sum = foldr (\x xs -> x + xs) 0
-- without fold:
sum [] = 0
sum (x : xs) = x + sum xs
-- what if:
sum = magic $ \case
[] -> 0
x : xs -> x + xs -- folding behavior without fold!
-- + more readable/maintainable- generalized
fold!- "cata" means "downwards" (down to a value)
- "always terminates"
- recursive entries of data structure are already their result
pretty :: Term -> String
pretty = foldTerm
id
(\x t -> "(λ" <> x <> "." <> t <> ")")
(\a b -> "(" <> a <> " " <> b <> ")")
show
(\a b -> "(" <> a <> " + " <> b <> ")")
(\a b -> "(" <> a <> " - " <> b <> ")")
(\a b -> "(" <> a <> " * " <> b <> ")")
(\a b -> "(" <> a <> " / " <> b <> ")")pretty :: Term -> String
pretty = cata $ \case -- special Term
Var x -> x
Fun x t -> "(\\" ++ s ++ " -> " ++ t ++ ")"
App a b -> "(" ++ a ++ " " ++ b ++ ")"
Num n -> show n
Add a b -> "(" ++ a ++ " + " ++ b ++ ")"
Sub a b -> "(" ++ a ++ " - " ++ b ++ ")"
Mul a b -> "(" ++ a ++ " * " ++ b ++ ")"
Div a b -> "(" ++ a ++ " / " ++ b ++ ")"freeVars :: Term -> Set String
freeVars (Var x)
= Set.singleton x
freeVars (Fun x t)
= Set.difference (freeVars t) (Set.singleton x)
freeVars (App a b)
= Set.union (freeVars a) (freeVars b)
freeVars (Num _)
= Set.empty
freeVars (Add a b)
= Set.union (freeVars a) (freeVars b)
freeVars (Sub a b)
= Set.union (freeVars a) (freeVars b)
freeVars (Mul a b)
= Set.union (freeVars a) (freeVars b)
freeVars (Div a b)
= Set.union (freeVars a) (freeVars b)freeVars :: Term -> Set String
freeVars = cata $ \case
Var x ->
Set.singleton x
Fun x t ->
Set.difference t (Set.singleton x)
names -> -- literally String Sets!
foldr Set.union Set.empty namesreplace every variable with a Term if it is in a Map
substituteBuiltin :: Map String Term -> Term -> Term
substituteBuiltin m = cata $ \case
Var name -> case Map.lookup name m of
Just term -> term
Nothing -> Var name
other -> Fix other -- WOAH!recursive Term in Term can be of any type now!
=> something like TermF t = Var String | Fun String t | App t t | ...?
data TermF t
= Var String
| Fun String t
| App t t
| ...
deriving (Functor, Foldable)
type Term1 = TermF TermF -- INVALID
type Term2 = TermF (TermF (TermF ())) -- INVALID
type Term* = TermF (TermF (TermF (TermF (..)))) -- ...=> magic wrapper type!
newtype Fix f = Fix { unFix :: f (Fix f) }
-- or: Mu for inductive/finite structures (least fixpoint)
-- Nu for coinductive/~infinite structures (greatest fixpoint)
type Term = Fix TermFnewtype Fix f = Fix { unFix :: f (Fix f) }
type Term = Fix TermF
-- we want:
cata :: (TermF a -> a) -> Term -> acata :: Functor f => (f a -> a) -> Fix f -> a
cata alg = alg . fmap (cata alg) . unFix
-- algebra = mapping from `f a` to `a`
-- where `f a` adds some context to `a`f (Fix f) --- fmap (cata alg) ----> f a
| |
| |
| |
| |
Fix alg
| |
| |
| |
v v
Fix f ------- cata alg -------> a
to define cata alg:
from Fix f ("Term") to a:
unFix -> fmap (cata alg) -> alg
{-# LANGUAGE TemplateHaskell #-}
import Data.Functor.Foldable
data Term
= Var String
| Fun String Term
| App Term Term
| ...
makeBaseFunctor ''Term
-- adds functor variations `VarF`, `FunF`, etc.
substituteBuiltin :: Map String Term -> Term -> Term
substituteBuiltin m = cata $ \case
VarF name -> case Map.lookup name m of
Just term -> term
Nothing -> Var name
other -> embed other -- embed ~= Fix- lists
- trees
cata is great, but sometimes we want the original structure!
reduce :: Term -> Term
reduce = cata $ \case
AppF func arg -> -- substitute arg _unreduced_
other -> embed otherreduceLinear :: Term -> Term
reduceLinear = para $ \case
AppF (_, Fun name body) (arg, _) ->
-- here: `body` is already reduced,
-- `arg` is not!
substitute name arg func
other -> embed (fmap fst other)-- substitue name with term in term
substitute :: String -> Term -> Term -> Term
substitute name replacement = cata $ \case
VarF n | n == name -> replacement
other -> embed othercata :: Functor f => (f a -> a) -> Fix f -> a
cata alg = alg . fmap (cata alg) . unFix
para :: Functor f => (f (Fix f, a) -> a) -> Fix f -> a
para alg = alg . fmap (\x -> (x, para alg x)) . unFixobvious!
corecursion & codata & unfold
fold= reduce/compress,unfold= expand/generate- codata is defined by its unfolding behavior
- lazy & potentially infinite (vs. traditional data)
- difference not relevant in most languages (non-total)
- corecursion produces potentially infinite codata
- (recursion consumes finite data)
foldr :: ((a, b) -> b) -> [a] -> b -- (tupled for duality)
unfoldr :: (b -> Maybe (a, b)) -> b -> [a]
unfoldr (\n -> if n == 0 then Nothing else Just (n, n - 1)) 5
~> [5,4,3,2,1]
replicate n v = unfoldr f n
where -- Coalgebra! a -> f a
f 0 = Nothing
f n = Just (v, n - 1)
replicate 5 'a'
~> "aaaaa"-- in Idris
data List a = Cons a (List a) | Nil
codata Colist a = Cons a (Colist a) | Nil
newtype Cofix f = Cofix { unCofix :: f (Cofix f) }
-- in Haskell it doesn't matter! (in Agda/Coq/Idris it does)- dual of
cata(corecursive) - generalized
unfoldr/iterate- "ana" means "upwards"
- no more
Maybe- end condition is encoded in Functor
ana :: Functor f => (a -> f a) -> a -> Fix f
ana coalg = Fix . fmap (ana coalg) . coalgcata :: Functor f => (f a -> a) -> Fix f -> a
cata alg = alg . fmap (cata alg) . unFix f (Cofix f) <-- fmap (ana coalg) ---- f a
^ ^
| |
| |
| |
unFix coalg
| |
| |
| |
| |
Cofix f <------ ana coalg ------- a
to define ana coalg:
from a ("seed") to Cofix f:
coalg -> fmap (ana coalg) -> unFix
generate infinite data structures
nats :: [Int]
nats = flip ana 0 $ \n -> Cons n (n + 1)or, generally, constructing longer sequences from parts
fib :: [Int]
fib = flip ana (0, 1) $ \case
(a, b) -> Cons a (b, a + b)
zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
zipWith f xs ys = flip ana (xs, ys) $ \case
([] , _ ) -> Nil
(_ , [] ) -> Nil
(x : xs, y : ys) -> Cons (f x y) (xs, ys)apois dual topara- what
paratocata, isapotoana
- what
anawith early exit (by "cotuple"Either)- continue unfold with new seed (
Right) - use already constructed term (
Left)
- continue unfold with new seed (
para :: Functor f => (f (Fix f, a) -> a) -> Fix f -> a
para alg = alg . fmap (\x -> (x, para alg x)) . unFixvs.
apo :: Functor f => (a -> f (Either a (Fix f))) -> a -> Fix f
apo coalg = Fix . fmap (either (apo coalg) id) . coalginsertOrd :: Ord a => a -> [a] -> [a]
insertOrd i = apo $ \case
[] -> Cons i (Left [])
h : t | h > i -> Cons i (Left (h : t))
h : t -> Cons h (Right t)
insertSort :: Ord a => [a] -> [a]
insertSort = cata $ \case
Nil -> []
Cons x xs -> insertOrd x xs- "refold": first construct, then collapse
- "hylo" = "matter" => form object from intermediate matter
hylo :: Functor f => (f b -> b) -> (a -> f a) -> a -> b
hylo alg coalg = cata alg . ana coalg
= alg . fmap (hylo alg coalg) . coalg -- no Fix!
cata alg = hylo alg unFix
ana coalg = hylo Fix coalgfac :: Int -> Int
fac = hylo alg coalg
where
coalg 0 = Nil
coalg n = Cons n (n - 1)
alg Nil = 1
alg (Cons n acc) = n * acc- construct
[n, n-1, ..., 1]by unfold (coalgebra) - collapse via multiplication by fold (algebra)
(fused/deforested in reality)
hylo can be used whenever recursive types are used intermediately
data BinTreeF a b = Tip | Branch b a b
deriving (Functor)
quicksort :: Ord a => [a] -> [a]
quicksort = hylo merge split
where
-- coalg for ana
split [] = Tip
split (x:xs) = let (l, r) = partition (< x) xs in Branch l x r
-- alg for cata
merge Tip = []
merge (Branch l x r) = l ++ [x] ++ rtime
cata/unfoldbut with access to any previous result- great for elegant memoization
histo :: Functor f => (f (Cofree f a) -> a) -> Fix f -> a
histo alg = extract . cata (\x -> alg x :< x)fib :: Natural -> Integer
fib = histo $ \case
Nothing -> 1
Just (_ :< Nothing ) -> 1
Just (a :< Just (b :< _)) -> a + bana/unfold with ability to determine the future of the unfold
futu :: Functor f => (a -> f (Free f a)) -> a -> Fix fgenerating trees or something?
combination of a histomorphism and futumorphism:
chrono :: Functor f => (f (Cofree f b) -> b) -> (a -> f (Free f a)) -> a -> busecase ??
zygoHistoPrepro
:: (Unfoldable t, Foldable t)
=> (Base t b -> b)
-> (forall c. Base t c -> Base t c)
-> (Base t (EnvT b (Stream (Base t)) a) -> a)
-> t
-> a
zygoHistoPrepro f g t = gprepro (distZygoT f distHisto) g tobvious, skipped
- less code & redundancy
- more clarity
- less potential for errors
- uniform APIs
- more generalization (composability + reusability)
- (co)algebras can be combined arbitrarily
- more optimizations
- laws implied by abstractness (e.g. fusion)
- compiler can see more clearly
- decouple how a function recurses from what it does
- scala: matryoshka
- haskell: recursion-schemes, data-fix
- your favorite fp language: something, probably
- Meijer, Fokkinga, Ross: "Functional Programming with Bananas, Lenses, Envelopes and Barbed Wire"
- blog series: https://blog.sumtypeofway.com/posts/introduction-to-recursion-schemes.html
- Tim Williams talk: https://www.youtube.com/watch?v=Zw9KeP3OzpU
- cheatsheets
- awesome recursion schemes: https://github.com/passy/awesome-recursion-schemes
*/