anon
anon

Reputation:

What does m >>= return means?

Was reading tutorial about monads and stuck on following:

let m = return 2 :: IO Int

That's understandable - we pack 2 in monadic variable(IO 2) But what does the following mean?

m >>= return

It outputs 2.

As I know from Monad definition, that return always accepts exactly one argument. However, here the argument absents. How it could be understood?

Upvotes: 0

Views: 86

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477265

(>>=) is the bind operator. It has signature:

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

So it expects (on the left side) a monadic object (for instance IO Int), and on the right side a function a -> m b (for instance Int -> IO b) here.

The operator is used to chain operations in a monad together. For instance putStrLn :: String -> IO () can be used if we use it like:

return "foo" >>= putStrLn

So now we return a string "foo". The bind operator will unwrap it out of the IO monad so to speak, and pass it to the putStrLn function that will print "foo" to the standard output channel, and return an IO (). We can then use that IO () for further processing.

Since return wraps data into a monad, writing >>= return is basically useless. Since for all x x >>= return should be equal to x.

The argument of return is not missing in the sense that >>= will call the return with an argument. You can also write:

m >>= (\x -> return x)

but this is equivalent to m >>= return.

Upvotes: 6

Related Questions