The program prints the nth number of Fibonacci series.
This program does not print anything. If you see the output, probably because you are calling it from read-eval- print -loop (REPL), which reads the form, evaluates it, and then prints the result. For example, you can do:
CL-USER> (fibonacci 4) 2
If you wrapped this call in another, you will see that it does not print anything:
CL-USER> (progn (fibonacci 4) nil) NIL
Since you have written this, it will be difficult to change it to print each fibonacci number only once, since you are doing a lot of redundant calculations. For example, a call
(fibonacci (- n 1))
will compute (fibonacci (- n 1)) , but so will the direct call
(fibonacci (- n 2))
This means that you probably don't want every fibonacci call to print the entire sequence. If you do this, note that (print x) returns the value x , so you can simply do:
(defun fibonacci(n) (cond ((eq n 1) 0) ((eq n 2) 1) ((print (+ (fibonacci (- n 1)) (fibonacci (- n 2)))))))
CL-USER> (progn (fibonacci 6) nil) 1 2 1 3 1 2 5 NIL
Here you will see several repeating parts, as there is redundant computation. However, you can calculate the series much more efficiently, starting with the first two numbers and counting:
(defun fibonacci (n) (do ((a 1 b) (b 1 (print (+ ab))) (nn (1- n))) ((zerop n) b)))
CL-USER> (fibonacci 6) 2 3 5 8 13 21