1

我想编写一个输出列表的函数。该函数获取一个列表并输出一个新列表。例如:

(0 0 1 2 2 1) -> (3 4 4 5 5 6)).

它的作用是:初始列表中的 index+1 是新列表中的值。并且该值在新列表中放置 x 次,具体取决于初始列表中的值。

(1 2) -> (1 2 2)
(0 3 0 3) -> (2 2 2 4 4 4)

所以 3 在第二个位置,值是 3,所以 2(第二个位置)在新列表中放置了 3 次。

我想出了这个,它不起作用

(defun change-list (list)
  (setq newlist '(1 2 3))
  (setq i 0) 
  (while (<= i (length list)) 
    (if (= (nth i list) 0)
      (concatenate 'list '0 'newlist)
    (concatenate 'list '(i) 'newlist))
    (+ i 1)
    (remove 0 newlist)))

问题主要在于它无法识别新变量。它给了我这些错误:functions.lisp:27:26: warning: Undefined function referenced: while

functions.lisp:31:2:警告:对未声明变量 newlist 的自由引用假定为特殊。警告:对我认为特殊的未声明变量的自由引用。

有没有人明白这一点?


我们能够自己解决它:

(defun change-list (a) 
  (loop for j from 1 to (length a) by 1 append 
    (loop for i from 1 to (nth (- j 1) a) by 1 
      collect j )))

这是一个更大的任务的一部分,我们没有得到太多关于 lisp 的教育,更像是:用 lisp 做。

4

3 回答 3

2

假设这是 Common Lisp,然后我将在您的代码中列出一些问题:

(defun change-list (list)
  (setq newlist '(1 2 3))

SETQ不声明变量,它只是设置它们。

  (setq i 0) 
  (while (<= i (length list)) 

WHILE在 Common Lisp 中不存在。

    (if (= (nth i list) 0)
      (concatenate 'list '0 'newlist)

0不是一个列表。因此你不能连接它。 CONCATENATE没有副作用。你在这里所做的一切都会丢失。 NEWLIST这是一个符号,而不是一个列表。不工作。

      (concatenate 'list '(i) 'newlist))

i这里不是变量。将其放入列表中将没有。 CONCATENATE没有副作用。你在这里所做的一切都会丢失。 NEWLIST这是一个符号,而不是一个列表。不工作。

    (+ i 1)

上面的效果就没有了。

    (remove 0 newlist)

上面的效果就没有了。

    ))
于 2012-06-26T17:03:21.210 回答
1

您可以简化对此的回答:

(defun change-list (list) 
  (loop for i in list and j from 1
        append (loop repeat i collect j)))
于 2012-06-26T17:38:52.437 回答
0

基本上,只是做同样事情的另一种方法:

(defun change-list (x)
  (let ((index 0))
    (mapcon
     #'(lambda (y)
         (incf index)
         (let ((z (car y)))
           (unless (zerop z)
             (make-list z :initial-element index)))) x)))

但可能对学习/谁知道你的教授期望什么有用。

于 2012-06-26T19:23:41.390 回答