asb
asb

Reputation: 4432

Lisp: why did `eval` lose favor after lexical scoping was introduced?

Just came across a quote from Peter Norvig in Paradigms in AI Programing:

In the past, eval was seen as the key to Lisp's flexibility. In modern Lisps with lexical scoping, such as Common Lisp, eval is used less often (in fact, in Scheme there is no eval at all). Instead, programmers are expected to use lambda to create a new function, and then apply or funcall the function.

There are considerations on why eval is not a good idea, such as this, however I am more interested in the interaction between eval and dynamic (special?) variables and how introduction of lexicals contributed to eval losing favor. What were some common eval idioms before the introduction of lexical variables?

Upvotes: 1

Views: 386

Answers (2)

Kevin Reid
Kevin Reid

Reputation: 43782

Unfortunately, I don't have a citation handy, but from what I remember hearing, the pattern that that text might be referring to is a way to emulate lexical scoping. That is, in lexical Common Lisp, we can simply write:

(defun constant-adder (a)
  (lambda (b) (+ a b)))

In a language which used dynamic scope for all variables (but with the same syntax otherwise), lexical scope could be emulated by constructing a lambda expression:

(defun constant-adder (a)
  (eval `(lambda (b) (+ (quote ,a) b))))

That is, we are constructing at runtime an expression which has the value of a substituted in, rather than having the language capture a automatically.

(However, your quote suggests that there was also no lambda in use. I have no plausible explanations for what would be happening in that case.)

Upvotes: 1

sds
sds

Reputation: 60014

eval

Evaluates form in the current dynamic environment and the null lexical environment.

This means that

(defun f (a) (eval '(1+ a)))
; warning: The variable A is defined but never used.

The compiler notices that, contrary to a naive expectation, a is not passed to eval. Indeed:

(f 10)
; error: UNBOUND-VARIABLE: The variable A is unbound.

Upvotes: 1

Related Questions