setq and defvar in Lisp

前端 未结 4 1394
梦谈多话
梦谈多话 2020-11-27 13:33

I see that the Practical Common Lisp uses (defvar *db* nil) for setting up a global variable. Isn\'t it OK to use setq for the same purpos

4条回答
  •  遥遥无期
    2020-11-27 14:37

    defvar and defparameter both introduce global variables. As Ken notes, setq assigns to a variable.

    In addition, defvar will not clobber something previously defvar-ed. Seibel says later in the book (Chapter 6): "Practically speaking, you should use DEFVAR to define variables that will contain data you'd want to keep even if you made a change to the source code that uses the variable."

    http://www.gigamonkeys.com/book/variables.html

    For instance, if you have a global *db* for the database in the Simple Database chapter:

    (defvar *db* nil)
    

    ...and you start playing with it at the REPL - adding, deleting things, etc - but then you make a change to the source file which contains that defvar form, reloading that file will not wipe out *db* and all the changes you might have made... I believe that setq will, as will defparameter. A more experienced Lisper please correct me if I'm wrong though.

提交回复
热议问题