Search code examples
haskellmonadsdo-notation

Haskell: trailing right arrow in a bind operation


From haskellwiki: expr1 >>= \x ->

I am curious about the right side of the (>>=) operator \x ->. What does it mean?

Nor \x -> nor \x is recognized by :type in GHCi.


Solution

  • To be clear, the section you're quoting is this:

    The actual translation from do notation to standard monadic operators is roughly that every expression matched to a pattern, x <- expr1, becomes

    expr1 >>= \x ->
    

    and every expression without a variable assignment, expr2 becomes

    expr2 >>= \_ ->
    

    All do blocks must end with a monadic expression, and a let clause is allowed at the beginning of a do block (but let clauses in do blocks do not use the in keyword). The definition of mothersPaternalGrandfather above would be translated to:

    mothersPaternalGrandfather s = mother s >>= \m ->
                               father m >>= \gf ->
                               father gf
    

    So as you can see, the -> is not actually trailing. If you look at the final example in the quotation above, where mothersPaternalGrandfather is defined, you'll see that the ->s all have a right hand side, which continues on the next line. The last line in the definition doesn't end with ->.

    As the text on the wiki explains, the expr1 >>= \x -> is just "roughly" what happens. You're right that expr1 >>= \x -> is not valid syntax. A more fully parenthesized version of the function definition would look like this:

    mothersPaternalGrandfather s =
      mother s >>= (\m -> father m >>= (\gf -> father gf))