[Haskell-cafe] The Applicative Functor Monad

Jeremy Shaw jeremy at n-heptane.com
Tue Dec 23 20:50:55 EST 2008


Hello,

I want to make a Monad which is almost exactly like the Writer monad,
except instead of using mappend to glue Monoids together, it uses <*>
to glue applicative functors together.

Here is the code:

import Control.Applicative
import Data.Monoid

-- * Sample Implementation of the Writer Monad

data Writer w a = Writer { runWriter :: (w, a) }

instance (Monoid w) => Monad (Writer w) where
    return a = Writer (mempty, a)
    (>>=) = bindWriter

bindWriter :: (Monoid w) => Writer w a -> (a -> Writer w b) -> Writer w b
bindWriter (Writer (w,a)) f =
    let (Writer (w', b)) = f a
    in Writer (w `mappend` w', b)

-- * Sample Implementation of the Applicative Functor Monad

data AF af a = AF { runAF :: (af, a) }

bindAF :: (Applicative f) => AF (f (a -> b)) x -> (x -> AF (f a) y) -> AF (f b) y
bindAF (AF (f, x)) g =
    let (AF (a, y)) = g x
    in AF (f <*> a, y)

-- instance (Applicative f) => Monad (AF (f ...

As you can see, the similarity is striking. Alas, AF and bindAF do not
quite have the right type signatures to be used for an instance of the
Monad class. Is there some clever work-around I missing? (Aside from,
-fno-implicit-prelude).

Thanks!

- jeremy


More information about the Haskell-Cafe mailing list