无法正确检索列表索引处的字符?

Ada*_*Lee 1 lisp global-variables common-lisp

我正在编写一个程序,它递归地迭代列表,提供当前字符的索引和字符列表。但是,当我运行以下程序时:

(defun printAllElementsRecursively (index providedList)
    (if (>= index (length providedList))
        (return-from printAllElementsRecursively NIL)
    )
    (defvar currCharacter (nth index providedList))
    (print (format nil "Character at index ~a: ~a" index currCharacter))
    (printAllElementsRecursively (+ index 1) providedList)
)

(printAllElementsRecursively 0 '(A B B A))
Run Code Online (Sandbox Code Playgroud)

我得到以下输出:

"Character at index 0: A" 
"Character at index 1: A" 
"Character at index 2: A" 
"Character at index 3: A" 
Run Code Online (Sandbox Code Playgroud)

考虑到 的值index确实正确增加,这看起来很奇怪。

sds*_*sds 5

您滥用了defvar

  1. 永远不应该在函数内部使用,应使用let代替或仅(nth index providedList)代替currCharacter

  2. 定义了一个新的全局变量,并且仅在尚未设置时才设置它,因此仅设置 currCharacter 一次

您也并不真正需要return-from,如果使用破折号而不是驼峰式大小写,您的代码将更具可读性。例如,

(defun print-list-elements-recursively (list)
   (when list
     (print (first list))
     (print-list-elements-recursively (rest list))))
Run Code Online (Sandbox Code Playgroud)

另外,它的列表nth参数的长度是线性的,所以你的函数是二次的(我的版本是线性的)。