0

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?

2 Answers 2

2

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?

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for the answer, basically, I added the loop you suggested right after the cond at the end of the function and called (pell 6) but it still prints this error: *** - *: (NIL (NIL)) is not a number
Nevermind, I just fixed my error, it works well and +1 for explanation!
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.