free-4.9: Monads for free

PortabilityGADTs, Rank2Types
MaintainerEdward Kmett <>
Safe HaskellNone




Applicative functors for free



Compared to the free monad, they are less expressive. However, they are also more flexible to inspect and interpret, as the number of ways in which the values can be nested is more limited.

See Free Applicative Functors, by Paolo Capriotti and Ambrus Kaposi, for some applications.

data Ap f a whereSource

The free Applicative for a Functor f.


Pure :: a -> Ap f a 
Ap :: f a -> Ap f (a -> b) -> Ap f b 


Functor (Ap f) 
Typeable1 f => Typeable1 (Ap f) 
Applicative (Ap f) 
Apply (Ap f) 

runAp :: Applicative g => (forall x. f x -> g x) -> Ap f a -> g aSource

Given a natural transformation from f to g, this gives a canonical monoidal natural transformation from Ap f to g.

runAp t == retractApp . hoistApp t

runAp_ :: Monoid m => (forall a. f a -> m) -> Ap f b -> mSource

Perform a monoidal analysis over free applicative value.


 count :: Ap f a -> Int
 count = getSum . runAp_ (\_ -> Sum 1)

liftAp :: f a -> Ap f aSource

A version of lift that can be used with just a Functor for f.

hoistAp :: (forall a. f a -> g a) -> Ap f b -> Ap g bSource

Given a natural transformation from f to g this gives a monoidal natural transformation from Ap f to Ap g.

retractAp :: Applicative f => Ap f a -> f aSource

Interprets the free applicative functor over f using the semantics for pure and <*> given by the Applicative instance for f.

retractApp == runAp id