Skip to content

Latest commit

 

History

History
892 lines (663 loc) · 17.8 KB

slides.md

File metadata and controls

892 lines (663 loc) · 17.8 KB
title recursion schemes
sub_title ana, cata, para, what?
date
theme
path
theme.yaml

recursion schemes
(in practice)

case study: Term

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))

traversing terms: pretty

data Term
  = Var String
  | Fun String Term
  | App Term Term
  | Num Integer
  | Add Term Term
  | Sub Term Term
  | Mul Term Term
  | Div Term Term
pretty :: 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 <> ")"

traversing terms: freeVars

data Term
  = Var String
  | Fun String Term
  | App Term Term
  | Num Integer
  | Add Term Term
  | Sub Term Term
  | Mul Term Term
  | Div Term Term
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)

common pattern in functional programming (trees, lists, graphs, etc.)

Recursive data structures are everywhere!

wild code demo

common solutions: generic traversals/rewrites/visitors

DEMO: in Effekt source/Tree

common solutions: custom folding function

data Term
  = Var String
  | Fun String Term
  | App Term Term
  | Num Integer
  | Add Term Term
  | Sub Term Term
  | Mul Term Term
  | Div Term Term
foldTerm :: (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)

pretty with foldTerm

data Term
  = Var String
  | Fun String Term
  | App Term Term
  | Num Integer
  | Add Term Term
  | Sub Term Term
  | Mul Term Term
  | Div Term Term
pretty :: 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

the problem with explicit recursion

  • 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

folding data == reduction to value

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

the CATAMORPHISM

  • 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 via cata

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 names

trivial default cases via cata

replace 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!

what is this Fix??

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 TermF

what is cata?!

newtype Fix f = Fix { unFix :: f (Fix f) }

type Term = Fix TermF

-- we want:
cata :: (TermF a -> a) -> Term -> a
cata :: 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

automagic functorization

{-# 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

wild catamorphisms demo

  • lists
  • trees

the PARAMORPHISM

cata is great, but sometimes we want the original structure!

reduce :: Term -> Term
reduce = cata $ \case
  AppF func arg -> -- substitute arg _unreduced_
  other -> embed other

introducing para!

reduceLinear :: 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 other

what is para?

cata :: 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)) . unFix

obvious!

wild paramorphisms demo

annotating additional information demo

corecursion & codata & unfold

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)

unfolding == expanding from seed

   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"

explicit dualization

-- 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)

the ANAMORPHISM

  • 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) . coalg
cata :: 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

use cases of ana??

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)

the APOMORPHISM

  • apo is dual to para
    • what para to cata, is apo to ana
  • ana with early exit (by "cotuple" Either)
    • continue unfold with new seed (Right)
    • use already constructed term (Left)
para :: Functor f => (f (Fix f, a) -> a) -> Fix f -> a
para alg = alg . fmap (\x -> (x, para alg x)) . unFix

vs.

apo :: Functor f => (a -> f (Either a (Fix f))) -> a -> Fix f
apo coalg = Fix . fmap (either (apo coalg) id) . coalg

insertion sort via apo

insertOrd :: 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

combinations: hylo

  • "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 coalg

fac via hylo

fac :: 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
  1. construct [n, n-1, ..., 1] by unfold (coalgebra)
  2. collapse via multiplication by fold (algebra)

(fused/deforested in reality)

refolds are common!

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] ++ r

time

the HISTOMORPHISM

  • cata/unfold but 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 + b

the FUTUMORPHISM

ana/unfold with ability to determine the future of the unfold

futu :: Functor f => (a -> f (Free f a)) -> a -> Fix f

generating trees or something?

the CHRONOMORPHISM

combination of a histomorphism and futumorphism:

chrono :: Functor f => (f (Cofree f b) -> b) -> (a -> f (Free f a)) -> a -> b

usecase ??

zygohistomorphic prepromorphism

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 t

obvious, skipped

why recursion schemes?

  • 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

in languages

  • scala: matryoshka
  • haskell: recursion-schemes, data-fix
  • your favorite fp language: something, probably

great resources

*/