5
votes

I was reading the purescript wiki and found following section which explains do in terms of >>=.

What does >>= mean?

Do notation

The do keyword introduces simple syntactic sugar for monadic expressions.

Here is an example, using the monad for the Maybe type:

 maybeSum :: Maybe Number -> Maybe Number -> Maybe Number 
 maybeSum a b = do   
     n <- a
     m <- b   
     let result = n + m   
     return result 

maybeSum takes two values of type Maybe Number and returns their sum if neither number is Nothing.

When using do notation, there must be a corresponding instance of the Monad type class for the return type. Statements can have the following form:

  • a <- x which desugars to x >>= \a -> ...
  • x which desugars to x >>= \_ -> ... or just x if this is the last statement.
  • A let binding let a = x. Note the lack of the in keyword.

The example maybeSum desugars to ::

 maybeSum a b =
   a >>= \n ->
     b >>= \m ->
       let result = n + m
       in return result
1

1 Answers

8
votes

>>= is a function, nothing more. It resides in the Prelude module and has type (>>=) :: forall m a b. (Bind m) => m a -> (a -> m b) -> m b, being an alias for the bind function of the Bind type class. You can find the definitions of the Prelude module in this link, found in the Pursuit package index.

This is closely related to the Monad type class in Haskell, which is a bit easier to find resources. There's a famous question on SO about this concept, which is a good starting point if you're looking to improve your knowledge on the bind function (if you're starting on functional programming now, you can skip it for a while).