The following line works as expected, but I am a little concerned why:
getLine >>= \x-> getLine >>= \y-> return [x, y]
Consider the addition of parenthesis to scope the lambda expressions:
getLine >>= (\x-> getLine) >>= (\y-> return [x, y])
The second line is errorneous because x
is not in scope when used in the return
, and I am happy with this. What concerns me this that in the first line the scope of x
appears to have 'leaked' out.
Is this 'leaking' considered bad practice? I am confused as to how it has remained in scope and not been lost immediately after the \x -> getLine
expression.
If you parenthesize your first line correctly according to haskell's precedence rules, you get:
getLine >>= (\x-> getLine >>= (\y-> return [x, y]))
This makes it obvious that the second lambda is inside the first, so there's no problem with it accessing the variables of the first lambda.
You parentheses are simply set wrong. The correct parentheses are
getLine >>= (\x -> getLine >>= (\y -> return [x, y]))
And therefore, x
is of course defined in the body.
Note that this feature is particularly useful since you can format code like this:
getLine >>= \x ->
getLine >>= \y ->
return [x, y]
which is almost
do
x <- getLine
y <- getLine
return [x, y]
but without any special syntax.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With