I am trying to display a Fibonacci sequence less than an upper bound, but I'm having trouble printing out the series that is constrained by that upper bound.
Without using imperative programming principles with declaring variables such as setf, setq, and set, etc. How can I solve this problem?
So far I have
(defun fibonacci (n &optional (a 0) (b 1))
(if (or (zerop n) (< a n)
nil)
(cons a (fibonacci (1- n) b ( a b)))))
Expected output of (fibonacci 100)
: (0 1 1 2 3 5 8 13 21 34 55 89)
. However, what I am getting is (0 1 1 2 3 5 8 13 21 34 55)
.
CodePudding user response:
You are decreasing upper bound for no reason. When you remove 1-
and move one )
to right place, it works as expected:
(defun fibonacci (n &optional (a 0) (b 1))
(if (or (zerop n) (> a n))
nil
(cons a (fibonacci n b ( a b)))))
Tests:
CL-USER 4 > (fibonacci 10)
(0 1 1 2 3 5 8)
CL-USER 5 > (fibonacci 100)
(0 1 1 2 3 5 8 13 21 34 55 89)
CodePudding user response:
What you meant is
(defun fibonacci (n &optional (a 0) (b 1))
(if (or (zerop n) (> a n))
nil
(cons a (fibonacci n b ( a b)))))
You had a )
placement typo / error, and the flipped test. Also, n
is the upper limit, not a count. So there's no reason to decrease it.