Reputation: 191
I would like to create a list with that contains the n
number of Pell Numbers. So far, I created everything and it's functional but I can't figure out a way to print a list of the numbers. Here is my code:
(defun pell (n)
(cond
( (= n 0) 0)
( (= n 1) 1)
( (= n 2) 2)
(t (+ (* 2 (pell (- n 1))) (pell (- n 2)))))
(loop for i from 1 to n doing
(list (pell i))))
Don't think it's correct, what am I missing?
Upvotes: 0
Views: 647
Reputation: 48745
This is related to the Fibonacci sequence and like all sequences like that you can iterate by keeping the needed last n numbers in a loop.
(defun pell (n)
(loop :for cnt :below n
:for a := 0 :then b
:for b := 1 :then c
:for c := 2 :then (+ (* 2 b) a)
:collect a))
Upvotes: 1
Reputation: 51501
You need to actually print the list, or, if testing on the REPL, return it so that the REPL prints it.
On the REPL, you might collect the values into a list and let the REPL print it:
> (loop :for i :below n
:collect (pell i))
⇒ (0 1 2 5 12 29)
Print to standard output:
(loop :for i :below n
:do (print (pell i)))
Note that the generally accepted formatting in Lisp looks like this (see e. g. http://gigamonkeys.com/book/syntax-and-semantics.html#formatting-lisp-code):
(defun pell (n)
(cond ((= n 0) 0)
((= n 1) 1)
((= n 2) 2)
(t (+ (* 2 (pell (- n 1)))
(pell (- n 2))))))
You also had a missing closing parenthesis in your function definition, and the loop calling it had one too many. You didn't want to do recursive calls in that loop, right?
Upvotes: 2