Budgetninja
Budgetninja

Reputation: 1

How to display fibonacci sequences less than upper bound (CLISP)

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).

Upvotes: 0

Views: 118

Answers (2)

Will Ness
Will Ness

Reputation: 71075

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.

Upvotes: 3

Martin Půda
Martin Půda

Reputation: 7568

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)

Upvotes: 3

Related Questions