6

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
porges
  • 30,133
  • 4
  • 83
  • 114
Nigel Thorne
  • 21,158
  • 3
  • 35
  • 51
  • > The do keyword introduces simple syntactic sugar for monadic expressions. 6 years later and this sentence still makes no sense at all – Code Whisperer Apr 27 '22 at 13:56
  • @CodeWhisperer .. "syntactic sugar" is just 'a nicer way to write the same thing. A monadic expression is an expression using modads. in this case the Maybe monad. Monads are types that wrap other types in order to make code composable/chainable Typically you wrap your base type... do your operations to the wrapped type,.. then unwrap the result to see what you got. The maybe monad handles null propergation. In this case `do` lets you skip some indentation making the code look more precedural – Nigel Thorne Apr 29 '22 at 05:46

1 Answers1

8

>>= 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).

Community
  • 1
  • 1
Mephy
  • 2,978
  • 3
  • 25
  • 31