It's because of lexical scoping.
(define f
(lambda () x))
Since x
is not in the lexical scope it has to be a global variable. Thus you can do the following:
(define x 10)
(f) ;=> 10
To make it a lexical variable it has to already exist at creation time:
(define f
(let ((x 10))
(lambda () x)))
In this example, since x
is a bound lexical variable the x
in the lambda is the same since the lambda inherits the environment from where it's evaluated.
Yes! A lambda
expression is evaluated so that it becomes a procedure object and define
assignes the global symbol f
to that object.
To prove that try to apply a list structure:
('(lambda (x) x) 10) ; gets error 'application: not a procedure'
In a LISP that has dynamic scoping the procedures doesn't have environments and the environment is takes from the runtime at call time:
(define (test)
some-value)
(define (call-test)
(let ((some-value 10))
(test))) ; => 10
(test) ; => error (unbound variable)
As you might see with dynamic scope it's difficult to tell if a procedure is correct or not as the environment it has when called changes for each call. Lexical scoping is also much easier for a compiler to optimize.