Guile includes a facility to capture a lexical environment, and later evaluate a new expression within that environment. This code is implemented in a module.
(use-modules (ice-9 local-eval))
Captures and returns a lexical environment for use with
Evaluate or compile the expression exp in the lexical environment env.
Here is a simple example, illustrating that it is the variable that gets captured, not just its value at one point in time.
(define e (let ((x 100)) (the-environment))) (define fetch-x (local-eval '(lambda () x) e)) (fetch-x) ⇒ 100 (local-eval '(set! x 42) e) (fetch-x) ⇒ 42
While exp is evaluated within the lexical environment of
(the-environment), it has the dynamic environment of the call to
local-compile can only evaluate
expressions, not definitions.
(local-eval '(define foo 42) (let ((x 100)) (the-environment))) ⇒ syntax error: definition in expression context
Note that the current implementation of
captures “normal” lexical bindings, and pattern variables bound by
syntax-case. It does not currently capture local syntax
transformers bound by
define-syntax forms. Any attempt to reference such
captured syntactic keywords via
local-compile produces an error.