(defun make-it-5 (num)
(setq num 5))
(setq a 0)
(make-it-5 a)
;; now a is still 0, not 5.在上面的代码中,似乎既没有(setq A 5)也没有(setq 0 5)发生。如果(Setqa5)发生了,那么a会变成5,但a仍然是0。如果发生(setq 0 5),就会发生Lisp错误。会发生什么?这就是我的问题。
对于你们中的一些人来说,通过谷歌搜索并想知道如何让它像它的名字那样工作,一种方法是
(defmacro make-it-7 (num) ; defmacro instead of defun
`(setq ,num 7))
(setq a 0)
(make-it-7 a)
;; now a is 7.另一个是:
(defun make-it-plus (num-var)
(set num-var (+ 1 (symbol-value num-var))) ; `set' instead of `setq'
)
(setq a 0)
(make-it-plus 'a) ; 'a instead of a
;; now a is 1.发布于 2011-01-27 03:52:07
简短的答案是(setq num 5) changes the binding for num,它是make-it-5函数的本地绑定。
下面是一个细目。确保您熟悉evaluation的概念是很好的。
当计算(make-it-5 a)时,解释器在表达式的第一个元素中查找函数。在本例中,第一个元素是一个符号(make-it-5 -这意味着它是一个named function),所以它在符号的function cell中查找。注意:此查找可以重复执行,请参阅Symbol Function Indirection。
计算表达式的其余元素以查找值。在本例中,只有一个符号(a),因此解释器返回the contents of its value cell,即0。
然后解释器将该函数应用于参数列表,这涉及到进行local bindings between its arguments to the values passed in。在这种情况下,在符号num和值0之间生成一个local binding。然后在该环境中计算函数体。
正文只是一个表达式,它是对setq的“调用”。我将“special form”放在引号中,因为setq是一个special form,不计算它的第一个参数,但查找符号并设置most local existing binding,这是在函数make-it-5内创建的绑定。
因此,您将更改函数make-it-5的本地符号num的绑定。
https://stackoverflow.com/questions/4808736
复制相似问题