Skip to content

Instantly share code, notes, and snippets.

@MasWag
Last active July 4, 2024 11:48
Show Gist options
  • Save MasWag/d01fea7173994259304f50fe86102b0b to your computer and use it in GitHub Desktop.
Save MasWag/d01fea7173994259304f50fe86102b0b to your computer and use it in GitHub Desktop.
A counterintuitive(?) behavior of dynamic binding demonstrated with Emacs Lisp
;; Static Binding
(setq lexical-binding t)
t
(defun addx (x)
(lambda (y) (+ x y)))
addx
(let ((add10 (addx 10))
(x 3))
(funcall add10 5)) ;; 10 + 5 = 15
15
;; Dynamic Binding
(setq lexical-binding nil)
nil
(defun addx (x)
(lambda (y) (+ x y)))
addx
(let ((add10 (addx 10))
(x 3))
(funcall add10 5)) ;; 3 + 5 = 8
8
;; The following is the same
(let ((x 3))
(funcall (addx 10) 5)) ;; 3 + 5 = 8
8
;; By the way, the following is the normal way to implement such a function in Emacs Lisp
(defun add2 (x y)
(+ x y))
add2
(let ((x 3)
(y 4))
(add2 5 6)) ;; 5 + 6 = 11
11
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment