Common Lisp special variables in closure

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)
Enjoyed this question?
Check out more content on our blog or follow us on social media.
Browse more questions