Reputation: 511
I'm new in Haskell, and I don't get it how this code works. Can anyone please explain it to me how the inner binding works in this example:
f = (\x -> ((\x -> x*x) 3)+x)
when I try f 1
I get 10
Upvotes: 1
Views: 266
Reputation: 25782
You code is quite obfuscated, so let’s clean it up. We start with
f = (\x -> ((\x -> x*x) 3)+x)
and notice that there are two variables that are both called x
– how confusing! So let’s write this as
f = (\x -> ((\y -> y*y) 3)+x)
Next, there is this inner lambda expression. We can give it a name and bind it at the same level as f
is bound:
square = (\y -> y*y)
f = (\x -> (square 3)+x)
At this point, I would like to remove unnecessary parenthesis:
square = \y -> y*y
f = \x -> square 3 + x
and finally, instead using a lambda abstraction, we can define square
and f
as functions. Again, this is equivalent code¹:
square y = y*y
f x = square 3 + x
At this point, you can probably make more sense of this code.
¹ In fact, the compiler might optimize the two different when it comes to inlining, which happens only when all manifest arguments are provided, but that is beyond the scope of this question.
Upvotes: 6
Reputation: 44878
You can safely remove the outer parentheses:
f = \x -> ((\x -> x*x) 3) + x
Now, the \x -> stuff
construct is an anonymous function of one argument x
. The very inner function \x -> x*x
squares any given number. (\x -> x*x) 3
calls it, which gives you 3 * 3 == 9
.
The outer function calls the inner one first and adds x
to the result. So, you get 9 + 1 == 10
.
I don't see anything special about binding here. The functions are independent, as well as the variables x
.
Upvotes: 1