没有正确检索列表索引处的字符



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

(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))

我得到以下输出:

"Character at index 0: A" 
"Character at index 1: A" 
"Character at index 2: A" 
"Character at index 3: A" 

考虑到index的值确实正确地递增,这似乎很奇怪。

您滥用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))))

此外,nth在其列表参数的长度中是线性,所以你的函数是二次函数(我的版本是线性函数(。

最新更新