12 ms·
So hga has the gist of the history, but here's a bit about the use of dynamic vs lexical scoping. Dynamic scoping allows you to do things like: (setq x 10)
by Jtsummers 16y ago
So hga has the gist of the history, but here's a bit about the use of dynamic vs lexical scoping.
Dynamic scoping allows you to do things like:
(setq x 10)
(defun foo (y) (+ x y))
(foo 3) ;; => 13
(let ((x -10))
(foo 3)) ;; dynamic => -7, lexical => 13
lexical scoping requires you to either explicitly pass this as a parameter:
(defun foo (y &optional (x 10)) (+ x y))
(foo 3) ;; => 13
(foo 3 -10) ;; => -7
or modify some value that is in the same scope as foo (lets assume they're both in the global scope for instance):
(setq x 10)
(defun foo (y) (+ x y))
(let ((old-x x))
(setf x -10)
(print (foo 3)) ;; -7
(setf x old-x))
The second one allows us to not change the definition of foo, and the former requires us to be aware that we need to pass this parameter through every function call until foo is reached.
On the other hand lexical scoping offers the possibility of closures which dynamic scope does not:
(defun bar (x) (lambda (y) (+ x y)))
In a lexically scoped language we can then do:
(funcall (bar 3) 10) ;; => 13
In a dynamically scoped language if x is not defined the above results in an error, and if it is defined we get something like:
(let ((x -10))
(funcall (bar 3) 10)) ;; => -7
Those are, of course, just two (simple) examples. All the above example code should work (unless I copied it wrong, next time I'm writing a comment like this in emacs with slime running) in emacs lisp and Common Lisp if you have either or both available to play with. In emacs lisp they demonstrate dynamic scope, and by using setq in CL it will demonstrate lexical scope. If you want to see dynamic scope in CL try running it with defvar instead.
Another example, this is to demonstrate that dynamic scope is also influenced by parameter names:
(setq x 10)
(defun foo (y) (+ x y))
(defun bar (x) (foo x))
(bar 3) ;; dynamic => 6, lexical => 13
This demonstrates a (potentially) major issue with dynamic scoping (at least as implemented by emacs lisp), that any free variables in functions can be altered by name collisions in any let or parameter list which may occur before it is reached.
Edit:
Found a couple discussions which add more than what I covered and better demonstrate the utility of dynamic scoping:
http://stackoverflow.com/questions/2979428/uses-for-dynamic-scope http://stackoverflow.com/questions/2979428/uses-for-dynamic-...
http://www.emacswiki.org/emacs/DynamicBindingVsLexicalBinding http://www.emacswiki.org/emacs/DynamicBindingVsLexicalBindin...