在Common Lisp中初始化计数器变量

Jor*_*rge 0 lisp common-lisp

我想在Common Lisp函数中使用一个变量作为计数器,从所需的数字开始并在循环中使用.

(defun x(c)
   (setq i 4)
   (loop while condition do 
        ;do something
        (incf i)))
Run Code Online (Sandbox Code Playgroud)

说明setq,incf并不适合这一点.在clisp中管理计数器变量的标准方法是什么?

cor*_*ump 8

LOOP§22中详细解释.黑带环圈.

(defun x (c)
  (loop 
    for i from 4 
    while <condition> 
    do <something>))
Run Code Online (Sandbox Code Playgroud)


Rai*_*wig 7

在Common Lisp中,您需要定义变量.您的变量i未定义.那是个错误.

(defun x (c)
   (setq i 4)                 ; undefined variable i
   (loop while condition do 
        ;do something
        (incf i)))            ; undefined variable i
Run Code Online (Sandbox Code Playgroud)

定义你的变量:

CL-USER 9 > (defun x (c)
              (let ((i 4))     ; defining/binding local variable i
                (loop while (< i 10) do
                      (print i)
                      (incf i))))
X

CL-USER 10 > (x :foobar)

4 
5 
6 
7 
8 
9 
NIL
Run Code Online (Sandbox Code Playgroud)

但正如coredump显示的另一个答案,loop提供了自己定义变量并迭代它的方法.