4

I am trying to understand Monad and I have the following code

f a b c d =
   do one <- a + b
      two <- c * d
      three <- one + two
      return three

The above compiles

but get the an error when I

*Main> f 1 2 3 4

:1:1:
    No instances for (Num (a0 -> t0), Monad ((->) a0), Monad ((->) t0))
      arising from a use of `f'
    Possible fix:
      add instance declarations for
      (Num (a0 -> t0), Monad ((->) a0), Monad ((->) t0))
    In the expression: f 1 2 3 4
    In an equation for `it': it = f 1 2 3 4

:1:9:
    No instance for (Num (a0 -> a0 -> t0))
      arising from the literal `4'
    Possible fix:
      add an instance declaration for (Num (a0 -> a0 -> t0))
    In the fourth argument of `f', namely `4'
    In the expression: f 1 2 3 4
    In an equation for `it': it = f 1 2 3 4

I think I would be one step closer to understand Monad if I know why the above code dont work on
f 1 2 3 4

5 Answers 5

8

The problem is you are confusing wrapped monadic values with pure values.

The first thing to know is that do notation is syntactic sugar for regular function calls (>>= and >>). So, it would help to see what your code desugars too.

Lets try something simpler

 f a b =
   do one <- a + b
      return one

This has the same problem as your code, but is simpler. To understand why it doesn't work we ask: what does this actually mean? Well, we can rewrite the <- symbol using >>=

 f a b = (a + b) >>= \x -> return x

(this is not the simplest representation, but makes the point clear)

If you test the following in GHCi

 >> :t (>>=)
 Monad m => m a -> (a -> m b) -> m b

that is, the function >>= takes: an argument of type m of a and a function from a to m of b and returns a m of b.

What about in this code?

(a + b)

Is going to be a number. How about the other half

 \x -> return x

Takes an object of type a and returns an object of type m a for any a

So, you need to have a number, that is also some sort of monad of something. Can you think of anything like that? It is not clear what this would be, which is a reason to be suspicious that this should type check.

One good way to come to terms with monads is to look at some specific examples.

The Maybe monad expresses computations that might fail

 instance Monad Maybe where
      return = Just
      (>>=) (Just a) f = f a
      (>>=) Nothing _ = Nothing

This lets you say things with a patter like

 f args = do x <- functionThatMightFail args
             y <- anotherfunctionThatMightFail x
             return y

or the same code more simply

f args = do x <- functionThatMightFail args
            anotherfunctionThatMightFail x

or perhaps

f args = functionThatMightFail args >>= anotherfunctionThatMightFail

On the other hand the List monad captures the idea of performing the same function on every element of a list, and then concatenating the results together. Simple examples abound:

f = do x <- [1,2,3,4]
       [1..x]

If you understand these ones, play with the State monad. It helps you get the more general idea that "monads are models of computation." I would then checkout Parsec, and of course, IO

0
8

I'm going to disagree with everyone else and say what you're doing almost certainly simply isn't related to monads. You probably just want to use some boring old code like this instead:

f a b c d = three where
    one = a + b
    two = c * d
    three = one + two

or more succinctly:

f a b c d = a + b + c * d
2
  • Isn't that what I pretty much said? :p
    – ivanm
    Nov 1, 2011 at 8:26
  • 1
    From a semantic perspective, every kind of "let" or evaluation order management is related to monads. In Haskell, the nice applicative syntax is reserved for the partiality monad (which some people call "pure"), and other monads have clunky syntax. The OP has a clear idea about which values the operators should act on, but Haskell requires either a monadic program with extra clunks inserted to manage the value-computation distinction, or (possible here) a retreat to the separate "pure" language. SHE gets the clunks down to f a b c d = (|(|a + b|) + (|c * d|)|), but that's still clunky.
    – pigworker
    Nov 1, 2011 at 8:59
3

I think you're confused about what the <- is used for. This operator "unpacks" data from within a monad; the IO monad in this case. For example, if you called readLn, you would receive a result of the type IO a. If you wanted to use the a inside the monad, you could put input <- readLn within a do construct, and that would bind the value of a to input. However, the value of a + b is not within the IO monad, or any monad. In your example use, a + b is simply of type Int. So if you want to declare a variable equal to that, you use a let statement: let one = a + b. The same goes for your other declarations. So you would want to rewrite this function as:

f a b c d = do
    let one = a + b
    let two = c * d
    let three = one + two
    return three

An additional note: adding type signatures can often help debug this sort of thing. If I add this type signature to your original function: f :: Int -> Int -> Int -> Int -> IO Int, I get a much more helpful error which says the expected type was IO t0, but the actual type was Int in the expression one <- a + b. This should help you realize that <- expects a monadic value as its right-side argument, but it received an Int instead.

0
1

Which Monad are you trying to use?

The closest match to what you're trying to do is the function monad ((->) a) (hence the GHC errors), but as you're supplying both arguments at each stage, this doesn't work.

Don't try to understand Monads in general by just banging code into do-blocks: understand how to use a particular Monad (e.g. learn how to use IO, learn how to use a monadic parsing library, etc.), and then understand the commonality that they have and how the Monad abstraction works.

Each Monad has its own unique characteristics and method of working (because if they didn't, then what's the point in having more than one?).

I particularly like Real World Haskell's approach to this: various Monads are introduced throughout with helper combinators to help manage the boilerplate, and then in Chapter 7 it's all brought together and the Monad typeclass is formally introduced.

1

In case you are trying to use a Maybe monad for error handling, here is a working example:

module Bbb where

import Data.Maybe

f a b c d =
   do one <- return $ a + b
      two <- return $ c * d
      three <- return $ one + two
      return three

main = print $ fromJust $ f 1 2 3 4

The import Data.Maybe clause is for fromJust, which is just

fromJust (Just x) = x

If you are just trying to interpret <- as assignments please don't :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.