如何在Lisp变量中保存追加返回?

时间:2017-02-14 21:30:15

标签: lisp common-lisp

(defun test(n x)
   (let* (d (append (list n) x)))
   (if (= n 0) d
      (test (- n 1) d)))

所以这是我在lisp中编写的基本测试函数。该函数应该带有一个数字(n)和一个列表(x),并将n和0之间的每个数字附加到返回的列表中。但是,当我运行它时,例如

(test 4 NIL)

它说

  

错误的绑定形式:( APPEND(LIST N)X)

基本上我的问题是如何将返回调用存储为附加到Lisp中的变量?

1 个答案:

答案 0 :(得分:3)

您在绑定周围缺少括号,并且您的代码不在let*的正文中,但在外部使d成为一个特殊的全局变量。你应该得到一个警告。由于您只使用一个绑定,因此不需要使用let*而不是let

(defun test (n x)
  (let ((d (append (list n) x)))
    (if (= n 0)
        d
        (test (- n 1) d))))

请注意,由于您要在列表的开头添加元素,因此应使用cons代替append + list,如下所示:

(defun test (n x)
  (let ((d (cons n x)))
    (if (= n 0)
        d
        (test (- n 1) d))))

我还注意到,如果您的基本情况更进一步,您就不需要绑定:

(defun make-range (to &optional (acc '()))
  "Makes a list of the elements from 0 to to"
  (if (< to 0)
      acc
      (make-range (- to 1) (cons to acc)))))

(make-range 5)
; ==> (0 1 2 3 4 5)
相关问题