You end the do
loop as soon as max
greater than sum
, which happens in the very first iteration.
After you switch this >
to <
, you get an arithmetic error, because ultimately you will bind sum
to nil
(when upgrading to (if (evenp curr) (+ sum curr))
, which is nil
when (evenp curr)
is false.You also need to specify an else-side: it must be sum
.
More importantly, do
binds its values ββin parallel, rather than in sequence, which means that for the second iteration, when you upgrade sum
to (if (evenp curr) (+ sum curr) sum)
you use curr
and sum
from the first iteration. If this is not what you intend, you should use do*
.
Update
As requested in the comments , here is the full working version of the code. Note that it is almost identical to the code in the question; it only reduces the order of the arguments to >
, so that completion occurs when the curr
ent of Fibonacci is greater than the value of imum max
, and adds the else case to the if
, so that when (evenp curr)
false, the sum
kept.
(defun sum-even-fibs (max) (do ((curr 0 next) (next 1 (+ curr next)) (sum 0 (if (evenp curr) (+ sum curr) sum))) ((> curr max) sum)))
source share