Some examples on closures and lexical-binding
See comments on r/emacs.
Hi Emacsers,
I've spent some time learning Elisp closures and lexical binding.
Although the documentation is clear with simple examples, I needed to to play with other examples to get my bearings.
As you might be interested, I will share them with you :)
The first section contains the info nodes and help corresponding to the examples.
The second section shows 10 "basic" examples using lexical-binding, lambda, defun, let, lexical-let, setq and defvar.
And the third section shows a more advanced example using lambda, let, dolist and defun.
Have a nice day,
ps: In the documentation we see that "Lexical binding is also more compatible with concurrency, which was added to Emacs in version 26.1.".
Does anyone know why this is? If so, can you indicate to me the files in the emacs source code where I can see these benefits? I'm really curious… thank you.
Info and help¶
Info nodes:
M-x eval-expression RET (info "(elisp)Variable Scoping")M-x eval-expression RET (info "(elisp)Closures")
help:
C-h v lexical-bindingC-h f defvarC-h f lambdaC-h f lexical-let
10 examples with lexical-binding, lambda, defun, let, lexical-let, setq, defvar¶
-
example 1
-
example 2
-
example 3
-
example 4
-
example 5
-
example 6
-
example 7
-
example 8
-
example 9
-
example 10
Advanced example using lambda, let, dolist, defun¶
Evaluating the following forms with lexical binding:
(setq lexical-binding t)
(defun call-f (f x)
`(:x-in-call-f ,x
:result-of-f ,(funcall f x)
:type-of-f ,(car f)
:env-of-f ,(and (eq (car f) 'closure) (cadr f))))
(dolist (x '(1 2 3))
(let ((f (lambda (y) `(:x-in-f ,x :y ,y))))
(message "%S" (append `(:x-in-dolist ,x) (call-f f -1)))))
prints out the following into the message buffer:
(:x-in-dolist 1
:x-in-call-f -1
:result-of-f (:x-in-f 1 :y -1)
:type-of-f closure
:env-of-f ((--dolist-tail-- 1 2 3) t))
(:x-in-dolist 2
:x-in-call-f -1
:result-of-f (:x-in-f 2 :y -1)
:type-of-f closure
:env-of-f ((--dolist-tail-- 2 3) t))
(:x-in-dolist 3
:x-in-call-f -1
:result-of-f (:x-in-f 3 :y -1)
:type-of-f closure
:env-of-f ((--dolist-tail-- 3) t))
Evaluating the following forms with dynamic binding:
(setq lexical-binding nil)
(defun call-f (f x)
`(:x-in-call-f ,x
:result-of-f ,(funcall f x)
:type-of-f ,(car f)
:env-of-f ,(and (eq (car f) 'closure) (cadr f))))
(dolist (x '(1 2 3))
(let ((f (lambda (y) `(:x-in-f ,x :y ,y))))
(message "%S" (append `(:x-in-dolist ,x) (call-f f -1)))))
prints out the following into the message buffer: