Search code examples
lispscopelexical-scope

Lisp warning: xx is neither declared nor bound, it will be treated as if it were declared SPECIAL


I am new to lisp and am writing a few simple programs to get more familiar with it. One of the things I am doing is writing a recursive and iterative version of a factorial method. However, I have come across a problem and can't seem to solve it.

I saw a similar error at Lisp: CHAR is neither declared nor bound but a solution wasn't actually reached, other than the OP realized he made a "typing mistake". In the REPL I can use the setf function and it works fine. I am also using LispBox with emacs. I would appreciate any suggestions!

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

WARNING in IT-FACT : RESULT is neither declared nor bound, it will be treated as if it were declared SPECIAL.


Solution

  • You need to bind the variable 'result' - using 'let', for example - before starting to use it:

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

    For futher details you might want to read this ...