Difference between type constructor and return function of a monad (in Haskell)

Viewed 807

I'm trying to figure out monads in Haskell but didn't get too far yet.

I found https://en.wikibooks.org/wiki/Haskell/Understanding_monads#cite_note-1 and several other tutorials/explanations, but none seems to be explaining the difference between the type constructor and the return function.

As I understood the

  • type constructor constructs a monad from a given value of the basic data type. So it's sort of a normal constructor like in Java, which builds from the given parameter a new instance.
  • return function applies the type constructor on the given value of the basic data type and returns the constructed monad.

So what's the point of having two functions doing basically the same?

EDIT So using the example of a Maybe-monad, the

  • country = Just "China": (constructor) creates the monad for the value "China".
  • return "China": returns the monad which is corresponding to the value of China, so it's basically the monad containing the "China" value.

Generally speaking I understand a monad as a container for values. One usage of monads is to combine simple/existing computations to more complex computations.

3 Answers

In

  (>>=) :: Monad m => m a -> (a -> m b) -> m b
  • m is a constructor of a type that is instance of the Monad class
  • m a is NOT a constructor application but a pattern matching to extract m and a
  • a->m b is a pattern against a function of m b. Let's call it k.
  • >>= needs to map to what k maps to ('returns'), i.e. apply k a

The implementation from Maybe

    (Just x) >>= k      = k x

In a do

  • >>= binds someMonad <- mConstructorSmartOrNot someParam to the next line
  • >> binds mConstructorSmartOrNot someParam to the next line
    return :: Monad m => a -> m a

return is basically the same as m, but since m can be any constructor (of a value of a variable of an m-constructed type), we can refer to it generally with this one name.

A monad constructs and forwards context.

Related