Created
May 24, 2012 15:09
-
-
Save michiakig/2782128 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
;; set two global variables | |
(setq x 'global-x) | |
(setq y 'global-y) | |
;; define a function that returns a nested function | |
(defun return-a-nested-fn (x) | |
;; the nested function takes no arguments and returns a list of two values | |
(lambda () (list x y))) | |
;; call that function, and call the function returned | |
(print (funcall (return-a-nested-fn 'local-x))) | |
;; in Emacs Lisp, which defaults to dynamic scope, this program will print: | |
;; (global-x global-y) | |
;; This is because when the nested function is called, the value of x | |
;; is global-x, even though that was not that value when the function | |
;; was defined | |
;; in Common Lisp, which defaults to lexical scope, this program will print: | |
;; (local-x global-y) | |
;; This is because when the nested function was defined, the value of | |
;; x was local-x, and this is _closed over_ when we create the nested | |
;; function and return it | |
;; in Emacs Lisp below will print (let-local-x global-y) | |
;; in Common Lisp, this will still print (local-x global-y) | |
(let ((x 'let-local-x)) | |
(print (funcall (return-a-nested-fn 'local-x)))) | |
;; Tested with Emacs and SBCL on OS X |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment