Newbie qustion about monads

Juanma Barranquero lektu at terra.es
Sun Oct 5 04:00:09 EDT 2003


On Thu, 02 Oct 2003 14:57:22 +0200, Juanma Barranquero <jmbarranquero at laley.wke.es> wrote:

> data Accum s a = Ac [s] a
> 
> instance Monad (Accum s) where
>    return x      = Ac [] x
>    Ac s1 x >>= f = let Ac s2 y = f x in Ac (s1++s2) y
> 
> output :: a -> Accum a ()
> output x = Ac [x] ()

After trying this one, and also

  output :: a -> Accum a a
  output x = Ac [x] x

I though of doing:

  data Accum a = Ac [a] a

because I was going to accumulate a's into the list.

That didn't work; defining >>= gave an error about the inferred type
being less polymorphic than expected ('a' and 'b' unified, etc.).

After thinking a while, I sort of understood that >>= is really more
polymorphic, i.e., even if it is constraining [s] to be a list (because
it is using ++), it really is saying nothing about the contents of the
list. It is "output" who's doing the constraint, but, with the very same
monad, I could do:

  output :: [a] -> Accum Int [a]
  output x = Ac [length x] x

or

  output :: a -> Accum [a] a
  output x = Ac [[x]] x

or whatever.

But then I wondered, is there any way to really define

  data Accum a = Ac [a] a

i.e., constraining it to use a for both values, and make a monad from it?

Curious,

                                                           Juanma



More information about the Haskell-Cafe mailing list