From: Pascal J. B. <pj...@in...> - 2012-04-25 04:19:35
|
"Yves S. Garret" <you...@gm...> writes: > Hi, going through Land of Lisp and I get to a part of the book where > you define global variables. I realize that the author is trying to > educate the students about this, but is there ever a good reason for > globals in Lisp? In Java, C/C++, PHP, etc. it's frowned down upon at > best. Functions, classes, types, constants, packages, etc, are global bindings. There are so many things that have global names, why do you worry about a few global variables? Yes, there are good reasons to have global variables. The main one is to keep references to "persistent" data. The scope of persistence being that of the lisp image (and remember that implementations provide operators to save the lisp images and reload them). Given the REPL, global variables allow passing data between two functions called independently, and with the programmer intervention at the REPL in the middle. cl-user> (defvar *data*) *data* cl-user> (defun compute-phase-a () (setf *data* (random 42))) compute-phase-a cl-user> (defun compute-phase-b () (* 2 *data*)) compute-phase-b cl-user> (compute-phase-a) 40 cl-user> *data* 40 cl-user> (compute-phase-b) 80 cl-user> *data* 40 Also, in Common Lisp global variables defined with defvar and defparameter are special variables. All the bindings involving the symbol naming them are dynamic bindings. This allow passing pervasive parameter unconspicuously. cl-user> (defun do-something () (print *data*) (terpri)) do-something cl-user> (setf *print-base* 16.) 10 cl-user> (do-something) 28 nil cl-user> (setf *print-base* 10.) 10 cl-user> (do-something) 40 nil -- __Pascal Bourguignon__ http://www.informatimago.com/ A bad day in () is better than a good day in {}. |