can someone please explain why is "ans" is bound to value of 16 in here after evaluation - this is a correct answer?
I thought the answer 3 since we're calling function f and sending values 1 and 2 as function f doesn't also see the values 5 and 10 but I guess I am wrong.
val x = 1
val y = 2
val f = fn y => x + y
val x = 5
val y = 10
val ans = f x + y
What you are seeing is sometimes called lexical scoping
. The function f
was defined in the scope of a certain binding for x
, that scope is the only scope that matters in understanding what f
does when f
is invoked. The fact that x
has a different meaning in the scope in which f
is invoked doesn't affect the meaning of f
itself. In the context of functional programming anything else would violate referential transparency. In the scope of a binding such as
val x = 1
it should be possible to freely replace x
by 1
. Thus your definition of f
should be equivalent to the definition:
def f y = 1 + y
as, indeed, it is.
I think I figured it out. Here goes:
fn f doesn't get evaluated until the end. So at:
val ans = f x + y
fn f gets called with the recent value x which is 5 because the value of the previous x is being shadowed. So at:
val f = fn y => x + y
the value received becomes the value of y. and here the function f takes the value the previous x which is 1 so that's a total of 6 (x comes from static environment). Then:
val ans = f x + y
we get back here: 6 + 10 = 16