OneEyeQuestion
OneEyeQuestion

Reputation: 742

How does this simple chained binding works?

I am learning Monads in Haskell and I am analyzing this example (http://learnyouahaskell.com/a-fistful-of-monads):

[1,2] >>= \n -> ['a','b'] >>= \ch -> return (n,ch)

I would like to understand what is happening in this part of the function:

\n -> ['a','b'] >>= \ch -> return (n,ch)

What I understand is that \ch -> return (n,ch) is being composed with \n -> ['a','b'] as argument, but I am not sure how is this happening. I was thinking that it had the following composed function:

[1,2] >>= \n -> [n, \n -> ['a','b']]

But that doesn't seem to output the same result as doing the full expression.

EDIT 1:

Taking into account an answer below the full parenthesization is:

[1,2] >>= ( \n -> ( ['a','b'] >>= \c -> return (n,c) ) )

Which led me to obtain this composed function:

[1,2] >>= ( \n -> [(n,'a'),(n,'b')] )

Upvotes: 1

Views: 117

Answers (1)

J. Abrahamson
J. Abrahamson

Reputation: 74354

It's actually a bit different than that. The parenthesization is as follows

[1,2] >>= (\n -> ['a','b'] >>= (\ch -> return (n,ch)))

Or, if you prefer

let step1 n = 
  let step2 ch = return (n, ch)
  in ['a','b'] >>= step2
in [1,2] >>= step1

Upvotes: 4

Related Questions