Common Lisp中的未绑定变量 [英] Unbound variable in Common Lisp
问题描述
我是Lisp的新手,我正在阅读ANSI Common Lisp第8章中的文本生成器示例。我遵循该示例,并在LET变量 prec的范围内定义了一个函数 see,
I'm new to Lisp and I was reading about an text-generator example in ANSI Common Lisp, Chapter 8. I follow the example and defined a function "see" in the scope of a LET variable "prec",
(let ((prec '|.|))
(defun see (symb)
(let ((pair (assoc symb (gethash prev *words*))))
(if (null pair)
(push (cons symb 1) (gethash prev *words*))
(incf (cdr pair))))
(setf prev symb)))
并保存
然后,当我返回REPL并尝试在加载文件的编译版本后调用see时,发生了错误:
Then when I returned to REPL and tried to invoke see after loading the compiled version of the file, an error occurred:
变量PREV是未绑定的。
[类型为UNBOUND-VARIABLE的条件]
如何正确调用外观?词汇闭包是做什么用的?我都很困惑。
How do I invoke see properly? And what's a lexical closure for? I'm all confused.
感谢您的帮助。
推荐答案
看起来您在封闭的 let $ c中键入了
prec
而不是 prev
$ c>形式。
Looks like you've typed prec
instead of prev
in the enclosing let
form.
词法闭包是封闭词法环境一部分的函数(因此而得名)。关于Lisp闭包的很多很好的介绍,在这里我将不再重复,但从本质上讲, let
是操纵词法环境的最常见方法;在这种情况下,您要添加上一个
的绑定,然后该绑定将可用于表单主体中的代码。您的函数 see
将关闭此绑定,因此即使对 see
的每次调用也可以访问它当您进行这些调用时,您将不再处于 let
表单所建立的词汇环境中。在某种意义上,您可以说函数定义使用了绑定。
Lexical closures are functions that 'close over' a part of the lexical environment (hence the name). There are many good introductions to closures in lisp that I will not attempt to repeat here but, essentially, let
is the most common way to manipulate the lexical environment; in this case, you want to add the binding for prev
, which will then be available to code within the body of the form. Your function see
will 'close over' this binding, and so each call to see
has access to it, even though when you make these calls, you will no longer be in the lexical environment established by the let
form. You could say the function definition takes the binding with it, in a sense.
由于您似乎错误输入了 prev的名称
,您的函数正在尝试引用代码中当时尚未建立的绑定。
As you appear to have mis-typed the name of the prev
, your function is trying to refer to a binding that has not been established at that point in the code.
这篇关于Common Lisp中的未绑定变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!