Assigning variables with setf, defvar, let and scope

后端 未结 2 1108
我在风中等你
我在风中等你 2021-01-06 01:51

So, I have read from
setq and defvar in lisp,
http://www.cs.ucf.edu/courses/cop4020/spr2006/plsetup.html, and
In Lisp, how do I fix "Warning: Assumed Spe

2条回答
  •  佛祖请我去吃肉
    2021-01-06 02:22

    I'll keep it short and simple:

    1) what is really going on with setf, defvar and let?

    • defvar and defparameter are used to declare and set globally special variables. They only differ when the name is already bound.

    • setf is used for assignment (to special variables, lexical variables, and other – possibly custom – setfable places.)

    • let (and let*) creates new variable bindings that are visible inside its body. It may create either lexical or special bindings, depending on (global or local) declarations. If there are no special declarations, lexical bindings will be created.

    2) is there a way to get common lisp to scope the variables inside a function as in the python example?

    Put the code inside let's body, where the binding is visible:

    CL-USER> (defun baz ()
               (let ((z 10))
                 (print z)
                 (incf z 10) ; i.e. (setf z (+ z 10))
                 (print z)))
    BAZ
    CL-USER> (baz)
    
    10 
    20 
    20
    CL-USER> z
    ; Evaluation aborted on #.
    

提交回复
热议问题