Adam Lee
Adam Lee

Reputation: 576

Not retrieving the character at an index of a list correctly?

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

Answers (1)

sds
sds

Reputation: 60004

You are misusing defvar:

  1. It should never be used inside a function, use let instead or just (nth index providedList) instead of currCharacter.

  2. 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

Related Questions