Haskell Language Recursion Schemes Primitive recursion


Example

Paramorphisms model primitive recursion. At each iteration of the fold, the folding function receives the subtree for further processing.

para :: Functor f => (f (Fix f, a) -> a) -> Fix f -> a
para f = f . fmap (\x -> (x, para f x)) . unFix

The Prelude's tails can be modelled as a paramorphism.

tails :: List a -> List (List a)
tails = para alg
    where alg Nil_ = cons nil nil  -- [[]]
          alg (Cons_ x (xs, xss)) = cons (cons x xs) xss  -- (x:xs):xss