使用追加拼合列表

时间:2018-11-06 16:36:20

标签: common-lisp

我正在编写Pell数字的迭代版本,我需要在列表中打印数字的输出。我已经做了所有事情,直到清单列出。而不是返回固定列表,它返回佩尔编号的单个列表。

我尝试附加所有单独的列表,但是它不起作用。我想念什么?

(defun iterPell (n)
  (let ((a 0) (b 1) (c n))
  (loop for i from 2 to n do
  (setq c (+ a (* 2 b))
       a b
       b c))
   c))

(dotimes (n 7)
  (write(append(list(iterPell n))))
)


>>(0)(1)(2)(5)(12)(29)(70)

1 个答案:

答案 0 :(得分:1)

(loop for n from 0 to 7
      collect (iterPell n))
;; => (0 1 2 5 12 29 70 169)

(let ((res)) ;; initialize collector = ((res nil))
  (dotimes (n 7) 
     (setf res (cons (iterPell n) res))) ;; setf the result new-value-consed
  (nreverse res)) ;; revert it (after all consing to beginning of list)
;; => (0 1 2 5 12 29 70 169)

;; or write recursive function
(defun apply-on-0-to-n (n func acc)
  (cond ((zerop n) (cons (funcall func 0) acc))
        (t (apply-on-0-to-n (1- n) func (cons (funcall func n) acc)))))

(apply-on-0-to-n 7 #'iterPell '())
;; => (0 1 2 5 12 29 70 169)