I’m trying the project euler problems to learn common lisp and I’m stuck pretty early. On problem 1, the question is the sum of integers from 1 to 1000. I think the code below should do it, but it always returns the value of end (if it’s mod 3 or mod 5) or 0 instead.
(defun mod3or5 (n)
(cond
((equal (mod n 5) 0) n)
((equal (mod n 3) 0) n)
(0))))
(defun mod-sum (start end)
(cond
((equal start end) (mod3or5 start))
(+ (mod3or5 start) (mod-sum (+ start 1) end))))
For example
(mod-sum 1 9)
=> 9
(mod-sum 1 8)
=> 0
I would expect the answers to be 23 and 14 respectively.
Each form given to
condhas the form(condition exp1 ... expn). Ifconditionis true, it will evaluate all the expressions and return the value ofexpn. Ifconditionis false, it will continue with the next form.Your last form is this:
(+ (mod3or5 start) (mod-sum (+ start 1) end)). So here+is the condition (which will always be true because+is a function and thus notnil),(mod3or5 start)is the first expression (which will be evaluated, but not returned) and(mod-sum (+ start 1) end)is the last expression (which will be evaluated and then returned).“Else branches” in
condare implemented by choosingtas the condition. So your last form should look like this: