How can I generate series of Pell numbers instead of a specific one in Lisp

前端 未结 3 1793
清酒与你
清酒与你 2021-01-21 15:27

How do I use cons or other way to print a list of Pell numbers till the Nth number?

(defun pellse (k)
   (if (or (zerop k) (= k 1))
       k
   (+ (* 2 (pellse (         


        
3条回答
  •  难免孤独
    2021-01-21 15:49

    One possible solution would be to use the LOOP macro of Common Lisp, e.g.:

    (print
        (loop for x in '(1 2 3 4 5 6 7)
          for y = (pellse x)
          collect y))
    

    That prints out the following result:

    (1 2 5 12 29 70 169)
    

    Based on this, you can build the following function:

    (defun list-of-n-pell-numbers (n)
        (loop for x from 0 to n
              for y = (pellse x)
              collect y))
    

    And run it like the following:

    (print (list-of-n-pell-numbers 7))
    (0 1 2 5 12 29 70 169)
    

    But please be careful when using this code, because your definition of pellse function is recursive, and has the risk of a stack overflow: make it call itself repeatedly enough (e.g. for big values of N), and it might blow up the call stack, unless you do some tail recursion. You might want to check the following explanations:

    • http://www.lispworks.com/documentation/lcl50/aug/aug-51.html
    • https://0branch.com/notes/tco-cl.html

提交回复
热议问题