LISP only retrieving first element of a list item
Вопрос
I have:
(defun getTotalValue(pack)
(cond ((null pack) 0)
(t (+ (car (car pack)))) (getTotalValue (cdr pack))
)
)
Which, to my understanding, will add up all the first elements of the items in a list. A test function call would be:
(getTotalValue '((10 c u) (3 s u) (5 h d) (7 s d) (12 h u)))
However, when I run the code above, it only prints out the first element of the first item in the list, 10
. Why won't it add up the first elements of all the items?
Решение
You had parenthesizing problem -- two misplaced close parenthesis after (car (car pack))
, so the cond
expression terminates there and the recursion happens but the result is thrown away.
(defun getTotalValue (pack)
(cond ((null pack) 0)
(t (+ (car (car pack)) (getTotalValue (cdr pack))))))
Не связан с StackOverflow