liveBook · Manning

Bind

As explained in Learn Haskell by Example

bind is the Monad operation that applies a function to the value produced by a monadic computation and returns the resulting monadic computation.

bind, written (>>=), sequences monadic computations. It takes a monadic value and a function that receives its inner value and returns the next monadic value: m a -> (a -> m b) -> m b. The next step runs only when the first computation produces a usable result. section 12.1.5

Propagating Maybe failures

With Maybe, bind passes a Just value to the next function, while Nothing stays Nothing. Chaining increment and multiplication turns Just 1 into Just 4; binding Nothing produces Nothing without running the next value-producing step. section 12.1.5

Nested binds can sequence dependent values, such as adding two monadic numbers. do notation is equivalent shorthand: `m >>= f` can be written as `do x <- m; f x`. Use `>>` when the first result should be ignored. section 12.1.5

Listing 12.13 A Monad instance for the parser type
instance Monad Parser where
  return = pure        #1
  (>>=) p f =
    Parser $ \t ->
      case runParser p t of     #2
        Left msg -> Left msg             #3
        Right (rest, x) -> runParser (f x) rest    #4

A Parser Monad instance runs the first parser, preserves failures, and supplies its parsed value and remaining input to the next parser. section 12.1.5

Parser code uses bind through do notation to parse dependent fields in order: a PNM header selects a magic number, then reads dimensions and an optional maximum value. Each later parser can use earlier results. section 12.1.5

How Learn Haskell by Example covers it

How deep it goes
Defines bind’s type, demonstrates Maybe behavior and do notation, and implements it for Parser.
Examples
Demonstrates chained Maybe arithmetic, monadic addition, Hello World parsing, integer parsing, and PNM header parsing.
What you can do after
Apply it via Haskell’s (>>=) and do notation to compose dependent Maybe and Parser computations.
How it connects
Connects Monad to Applicative, Maybe, do notation, return, Parser, and parsing failures.

Also explained in

Compare how 5 books explain bind →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Haskell by Example. The section links point to the parts of the book it draws on.