I'm somewhat confused regarding dynamical scoping, specifically what happens when a formal parameter and a free variable share a name.
For example
(define x 1)
(define f (lambda (x) x) )
(f 2)
If this code is compiled and evaluated using dynamic scoping, what would be the input? 2 or 3?
While it seems as if the assignment (x = 2) from the parameter is the most 'recent' so it should be '2', some have told me the answer is 1 (and others said its 2. Everyone is confused).
{I know scheme and most languages use lexical scoping, but tell that to my professor}
I would appreciate any help I can get.
There is no dynamic scoping. It is either "lexical scoping" or "dynamic extent". But, putting that aside, it's 2:
(f 2)
=
( (lambda (x) x) 2 )
=
(begin (set! old-x x) ; save old value of formal param
(set! x 2) ; set param to argument's value
(set! return-value ; evaluate the body
x) ; and save the result
(set! x old-x) ; restore the param's old value
return-value ) ; return the result
The translation must use unique names for the temporary variables throughout, to prevent any mix-ups. Here it's old-x
and return-value
but it could be any name not used anywhere else in the translated program code.