I still do not understand how a dynamic interpreter differ from a lexical one.
I am working on scheme and i find it very difficult to know how a simple code like these one works dynamically and lexically.
(define mystery
(let ((x 2018))
(lambda (y)
(let ((result (cons x y)))
(set! x (+ x 1))
result))))
any guidance?
Lexical bindings have limited visibility and unlimited lifespan. All functions "remember" environment, where they were created- that kind of functions is called lexical closures.
In your example, this part:
returns function, which remembers environment with x = 2018. That function is bind to symbol
mysteryand when you call it, it changes value of x in that environment.In Scheme with dynamic bindings (unlimited visibility, limited lifespan), functions don't remember environment, where they were created. So, function
mysterywon't remember environment with x = 2018 and call(mystery 1)ends with error during evaluation of(cons x y), because symbolxhas no value.