[Haskell-cafe] Strict Monad

Álvaro García Pérez agarcia at babel.ls.fi.upm.es
Wed Nov 4 18:58:54 EST 2009


Hi,

I'm trying to characterise some strict monads to work with a particular
lambda-calculus evaluator, as an alternative to CPS monad.

In the thread "Stupid question #852: Strict monad" the implementation of
some strict monads (and pseudo-monads, not meeting the identity laws) is
discussed. It's clear form that thread that using pattern-matching in the
(>>=) operation will force evaluation, then the Id monad defined with
pattern-matching is strict (and it's indeed a monad):

> newtype Id a = Id a
>
> instance Monad Id where
>     return = Id
>     (Id a) >>= f = f a

But it's impossible to derive a monad transformer from it, because you don't
know the constructors of the monads you're transforming. I then tried to use
strict application ($!). My first attempt was

> newtype Strict a = InSt { outSt :: a }
>
> instance Monad Strict where
>     return = InSt
>     m >>= f = (\x -> f x) $! (outSt m)

which is not a monad (doesn't meet the left identity law).

    (return undefined) >>= (\x -> const (return 1) x)
=/=        (return 1)

Then I wondered if it was enough to force the evaluation of the whole monad,
instead of the value inside the monad, yielding the second attempt:

> newtype Strict a = InSt { outSt :: a }
>
> instance Monad Strict where
>     return = InSt
>     m >>= f = (\x -> f (outSt x)) $! m

I placed the outSt inside the anonymous function, leaving the monad on the
right of the ($!). This meets the identity laws and surprisingly (I was
expecting a lazy behaviour) implements strict semantics (it behaves like
CPS, which is strict as well). A transformer from this monad can be easily
written:

> newtype StrictT m a = InStT { outStT :: m a }
>
> instance Monad m => Monad (StrictT m) where
>     return = InStT . return
>     m >>= t = InStT $ (\x -> x >>= (\a -> outStT $ t a)) $! (outStT m)
>
> instance MonadTrans StrictT where
>     lift = InStT

Is it common practice to use this monad and this transformer? Why is it not
in the standard library? I looked for this monad in the literature but I
didn't find anything similar. It seems naive to me that this has never been
previously described. Am I doing something wrong and this is not a monad at
all?

Alvaro.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20091104/408c9b25/attachment.html


More information about the Haskell-Cafe mailing list