Reputation: 89
so I'm new to LISP and I was wondering how I could find the sum of numbers that are divisible by 3. Here's what I have done so far:
(defun sumel (li)
(cond
((null li) 0)
( (zerop (rem (car li) 3)) (+ (car li) (sumel (cdr li))))
)
)
A little hint to what I'm doing wrong would be great.
Upvotes: 0
Views: 237
Reputation: 2148
You can also take a different approach which utilizes the large standard library of Common Lisp (remove-if-not
and reduce
in this case)
(defun sumel (list)
(reduce '+ (remove-if-not (lambda (x) (zerop (rem x 3)))
list)))
Upvotes: 0
Reputation: 48745
You hanve the case where the list is empty and when you actually find a multiple of 3, but what happens if it is a nother number you should skip? You have do default term so Common Lisp will return nil
. Eg your code works like this:
(defun sumel (li)
(cond
((null li) 0)
((zerop (rem (car li) 3))
(+ (car li) (sumel (cdr li))))
(t nil))) ; when not a multiple of 3 we are finished, return nil
Try evaluating (cond)
and you'll see it is the same as (cond (t nil))
.
You fix this by adding just (sumel (cdr l))
as the alternative. It should evaluate to the sum of the multiples of the rest of the list, which is what you want.
Upvotes: 3