Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Local dynamic binding in common lisp

Honnestly, I'm not sure I fully understand what it means for a binding to be "dynamic" versus "lexical". But I understand that when I use defvar or defparameterto define a binding, 1. it declares a global variable 2. the binding is declared "special", so that it can be shadowed by a new local binding, e.g.

(defvar *x* 3)
(defun f () *x*)
(f) ;=>3
(let ((*x* 2)) (f));=>2

Now, my question is, would it be possible to have a local binding(i.e. a binding that doesn't pollute the global environment) that has the same property(i.e. that can be shadowed by "outer"/"newer" bindings)?

Example:

(special-binding ((x 1)) (defun f () x))
(f);=>1
x;=>error, no binding in the global environment
(let ((x 2)) (f));=>2

I tried using (special x) declarations in let block, or (locally (declare (special x)) ...), but it doesn't seem to create closures(asking for the value of the variable from a function defined that way triggers an "Unbound-Variable" error).

like image 682
Charles Langlois Avatar asked May 02 '26 11:05

Charles Langlois


1 Answers

You can't capture dynamic bindings in a closure, only lexical bindings.

You need to declare the variable special in the function, so it will use the dynamic binding:

(defun f () 
  (declare (special x))
  x)

Then you need to bind the variable dynamically around the call, with:

(let ((x 1))
  (declare (special x))
  (f))
like image 197
Barmar Avatar answered May 04 '26 14:05

Barmar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!