1

I have a function

add2Maybe :: (Num a) => Maybe a -> Maybe a -> Maybe a
add2Maybe x y = do
    n1 <- x
    n2 <- y
    return $ n1 + n2

It will successfully return Just 8 when called with Just 3 and Just 5. What I want is when this fuction is called, similar to printf debugging in C, printing

The number in x is 3. --(Or Nothing).
The number in y is 5.
Final result is 8.

and return Just 8.

I concluded that to define a function like this, I have to use Maybe monad with IO monad, but the type signiture of >>= doesn't allow to use more than two monad in a single function. Is there a way to combine Maybe monad and IO monad, and more generally, is there a way to combine two or more monad types?

SAN
  • 69
  • 3

2 Answers2

6

You are looking for a "monad transformer". Just as values of type IO a and Maybe a are monads, so too can be a value of type IO (Maybe a). This combination uses MaybeT.

However, this is a bit of an advanced topic, and will have you scratching your head if you are new to the concepts. If you just want to do printf-style debugging, consider Debug.Trace instead. It lets you cheat the type system to get text output when debugging, but should never be used in a finished program.

amalloy
  • 89,153
  • 8
  • 140
  • 205
2

If you just need add2Maybe implementation here it is

add2Maybe :: (Show a, Num a) => Maybe a -> Maybe a -> IO (Maybe a)
add2Maybe x y = do
                 mapM print x
                 mapM print y
                 return $ do 
                  n1 <- x
                  n2 <- y
                  return $ n1 + n2
talex
  • 17,973
  • 3
  • 29
  • 66