Common Lisp special variables in closure

Common Lisp special variables in closure
typescript
Ethan Jackson

I'm stumbling on a problem to capture special variables:

This works:

(let ((a 2)) (declare (special a)) (funcall (lambda (x) (declare (special a)) (+ a (* x 3))) 3)) => 11

But this doesn't work:

(funcall (let ((a 2)) (declare (special a)) (lambda (x) (declare (special a)) (funcall (lambda (x) (declare (special a)) (+ a (* x 3))) x))) 3) => The variable a is unbound.

It seems, a closure can't be used for dynamic scope. Is there a way to get it done without polluting the global namespace?

Answer

I found the following solution, which works in my use-case:

(funcall (lambda (x) (let ((a 2)) (declare (special a)) (funcall (lambda (x) (declare (special a)) (+ a (* x 3))) x))) 3)

Related Articles