Static Scope in Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
def A(): print x # global x def B(): def C(): x = "C's x" print x # local x D() def D(): print x # nonlocal x x = "B's x" print x # local x A() C() x = "Global x" B() # Output: # moxie - dschlege - csc344 > python scope.py # B's x # Global x # C's x # B's x |
Static vs Dynamic Scope in Common Lisp and Emacs Lisp
Common Lisp:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
cl-user(1): (setf x 1) 1 cl-user(2): (defun outer (x) (inner)) outer cl-user(3): (defun inner () x) inner cl-user(4): (outer 2) 1 cl-user(5): (inner) 1 |
[Note that Common Lisp does have global variables with dynamic scope when defined with defvar or defparameter. Local dynamically scoped variables can be created and referred to with the rarely used special declaration.]
Emacs Lisp:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
(setf x 1) 1 (defun outer (x) (inner)) outer (defun inner () x) inner (outer 2) 2 (inner) 1 |
(The above examples were adapted from https://www.cse.buffalo.edu/~shapiro/Courses/CSE305/Notes/notes6.html)
Dynamic Scope in Bash
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
str="begin" echo "start: str=$str" function inner { echo "inner: str=$str" } function outer { local str="outer" inner } outer echo "end: str=$str" # Output: # start: str=begin # inner: str=outer # end: str=begin |
Static Scope in Clojure
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
$ lein repl user=> (def x 2) user=> (let [x 3] (defn a [] (println "x=" x) (let [x 4] (println "x=" x)))) #'user/a user=> (a) x= 3 x= 4 nil user=> (println x) 2 |
Dynamic Scope in Clojure
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
$ lein repl user=> (def ^:dynamic x 1) #'user/x user=> (def ^:dynamic y 2) #'user/y user=> (defn printvars [] (print "x: " x " y: " y "\n")) #'user/printvars user=> (printvars) x: 1 y: 2 nil user=> (binding [x 2 y 3] (printvars)) x: 2 y: 3 nil user=> (binding [x 2 y 3] (printvars) (binding [x 3 y 4] (printvars)) (printvars)) x: 2 y: 3 x: 3 y: 4 x: 2 y: 3 nil user=> (printvars) x: 1 y: 2 nil user=> |