[Haskell-cafe] beginner's problam with a monad

Julien Oster haskell at lists.julien-oster.de
Sun Sep 3 13:25:40 EDT 2006


Hello,

after succeeding in implementing my first monad (Counter, it increments
a counter every time a computation is performed) I though I'd try
another one and went on to implement "Tracker".

"Tracker" is a monad where a list consisting of the result of every
computation is kept alongside the final value, kind of a computation
history. It really just serves me as an exercise to implement monads.

However, the following source code fails:

{-------------------------------------------------}

data Tracker a b = Tracker [a] b
             deriving Show

instance Monad (Tracker a) where
    m >>= f =
        let Tracker l x = m in
            let Tracker l' x' = f x in
                Tracker (x':l) x'
    return x = Tracker [] x

bar = do
  x <- Tracker [] 12
  y <- return (x*2)
  z <- return (y*3)
  return (z+3)

{-------------------------------------------------}

Of course, style recommendations and the like are always appreciated.

(by the way, I don't really understand why I have to type
  instance Monad (Tracker a)
instead of
  instance Monad Tracker
which may very well be the problem. If it's not, can someone tell me
anyway?)

Trying to load this piece of code leads to the following error message:

Hugs.Base> :load Test.hs
ERROR "Test.hs":30 - Inferred type is not general enough
*** Expression    : (>>=)
*** Expected type : Monad (Tracker a) => Tracker a b -> (b -> Tracker a
c) -> Tracker a c
*** Inferred type : Monad (Tracker a) => Tracker a b -> (b -> Tracker a
a) -> Tracker a a

Why does the interpreter infer Tracker a a instead of the more general
Tracker a c?

Thanks,
Julien


More information about the Haskell-Cafe mailing list