Reputation: 576
I am writing a program that recursively iterates through a list, provided the index of the current character and a list of characters. However, when I run the following program:
(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))
I get the following output:
"Character at index 0: A"
"Character at index 1: A"
"Character at index 2: A"
"Character at index 3: A"
This seems strange, considering that the value of index
does increment correctly.
Upvotes: 1
Views: 74
Reputation: 60004
You are misusing defvar
:
It should never be used inside a function, use let
instead or just (nth index providedList)
instead of currCharacter
.
It defines a new global variable, and only sets it if it has not been set yet, so it sets
currCharacter
once only.
You also do not really need return-from
, and your code
would be more readable if use used dashes instead of camel case.
E.g.,
(defun print-list-elements-recursively (list)
(when list
(print (first list))
(print-list-elements-recursively (rest list))))
Also, nth
is linear in its list argument's length,
so your function is quadratic in it (my version is linear).
Upvotes: 5