|
| 1 | +{-# LANGUAGE DefaultSignatures #-} |
| 2 | +{-# LANGUAGE QuantifiedConstraints #-} |
| 3 | +{-# LANGUAGE UndecidableInstances #-} |
| 4 | + |
| 5 | +module Unison.Util.Recursion |
| 6 | + ( Algebra, |
| 7 | + Recursive (..), |
| 8 | + cataM, |
| 9 | + para, |
| 10 | + Fix (..), |
| 11 | + Cofree' (..), |
| 12 | + ) |
| 13 | +where |
| 14 | + |
| 15 | +import Control.Arrow ((&&&)) |
| 16 | +import Control.Comonad.Cofree (Cofree ((:<))) |
| 17 | +import Control.Monad ((<=<)) |
| 18 | + |
| 19 | +type Algebra f a = f a -> a |
| 20 | + |
| 21 | +class Recursive t f | t -> f where |
| 22 | + cata :: (Algebra f a) -> t -> a |
| 23 | + default cata :: (Functor f) => (f a -> a) -> t -> a |
| 24 | + cata φ = φ . fmap (cata φ) . project |
| 25 | + project :: t -> f t |
| 26 | + default project :: (Functor f) => t -> f t |
| 27 | + project = cata (fmap embed) |
| 28 | + embed :: f t -> t |
| 29 | + {-# MINIMAL embed, (cata | project) #-} |
| 30 | + |
| 31 | +cataM :: (Recursive t f, Traversable f, Monad m) => (f a -> m a) -> t -> m a |
| 32 | +cataM φ = cata $ φ <=< sequenceA |
| 33 | + |
| 34 | +para :: (Recursive t f, Functor f) => (f (t, a) -> a) -> t -> a |
| 35 | +para φ = snd . cata (embed . fmap fst &&& φ) |
| 36 | + |
| 37 | +newtype Fix f = Fix (f (Fix f)) |
| 38 | + |
| 39 | +deriving instance (forall a. (Show a) => Show (f a)) => Show (Fix f) |
| 40 | + |
| 41 | +deriving instance (forall a. (Eq a) => Eq (f a)) => Eq (Fix f) |
| 42 | + |
| 43 | +deriving instance (Eq (Fix f), forall a. (Ord a) => Ord (f a)) => Ord (Fix f) |
| 44 | + |
| 45 | +instance (Functor f) => Recursive (Fix f) f where |
| 46 | + embed = Fix |
| 47 | + project (Fix f) = f |
| 48 | + |
| 49 | +data Cofree' f a x = a :<< f x |
| 50 | + deriving (Foldable, Functor, Traversable) |
| 51 | + |
| 52 | +-- | |
| 53 | +-- |
| 54 | +-- __NB__: `Cofree` from “free” is lazy, so this instance is technically partial. |
| 55 | +instance (Functor f) => Recursive (Cofree f a) (Cofree' f a) where |
| 56 | + embed (a :<< fco) = a :< fco |
| 57 | + project (a :< fco) = a :<< fco |
0 commit comments