Lisp警告:xx既未声明也未绑定,它将被视为声明为SPECIAL

时间:2009-09-06 08:18:06

标签: lisp scope lexical-scope

我是lisp的新手,正在编写一些简单的程序来熟悉它。我正在做的一件事是编写一个阶乘方法的递归和迭代版本。但是,我遇到了一个问题,似乎无法解决它。

我看到了类似的错误 Lisp: CHAR is neither declared nor bound 但实际上没有达成解决方案,除了OP意识到他犯了“打字错误”。在REPL中我可以使用setf函数,它工作正常。我也在使用带有emacs的LispBox。我很感激任何建议!

(defun it-fact(num)
  (setf result 1)
  (dotimes (i num)
    (setf result (* result (+ i 1)))
  )
)

IT-FACT中的警告: RESULT既未声明也未绑定, 它将被视为特别声明。

3 个答案:

答案 0 :(得分:7)

有一些错误或不太好的Lisp风格:

(defun it-fact(num)                      ; style: use a space before (
  (setf result 1)                        ; bad: variable RESULT is not introduced
  (dotimes (i num)
    (setf result (* result (+ i 1)))     ; bad: extra addition in each iteration
  )                                      ; style: parentheses on a single line
)                                        ; bad: no useful return value

可能的版本:

(defun it-fact (num)
  (let ((result 1))                      ; local variable introduced with LET
    (loop for i from 1 upto num          ; I starts with 1, no extra addition
      do (setf result (* result i)))
    result))                             ; result gets returned from the LET

答案 1 :(得分:6)

你需要绑定变量'result' - 例如使用'let' - 在开始使用它之前:

(defun it-fact(num)
  (let ((result 1))
    (dotimes (i num)
      (setf result (* result (+ i 1))))))

有关详细信息,您可能需要阅读this ...

答案 2 :(得分:6)

在Lisp中,必须使用LET或其他创建局部变量的表单显式声明局部变量。 这不同于例如Python或JavaScript,其中赋值给变量在当前词法范围内创建变量。

您的示例可以像这样重写:

(defun it-fact(num)
  (let ((result 1))
    (dotimes (i num)
      (setf result (* result (+ i 1))))))

一个偏离主题的评论:将右括号放在不同的行上是没有意义的。