合并列表列表并循环返回

时间:2016-11-27 06:26:32

标签: list merge lisp common-lisp

我正在尝试将所有列表列表合并为一个。

到目前为止,这是我的代码:

(DEFUN DESCRIPTION (BLOCK)
    (loop initially (setf result '())
        for desc in (DESC2 BLOCK) 
        do (append result desc)
        finally (return result)
        )
)

函数(DESC2 BLOCK)返回以下内容:

((SHAPE BRICK) (COLOR GREEN) (SIZE SMALL) (SUPPORTED-BY B2) (SUPPORTED-BY B3))

我只需要函数返回合并列表:

(SHAPE BRICK COLOR GREEN SIZE SMALL SUPPORTED-BY B2 SUPPORTED-BY B3)

我已经尝试了很多方法并且已经研究了很多。我很抱歉,但我不完全了解LISP语言,如果你能帮助我,我将不胜感激!

提前谢谢!

1 个答案:

答案 0 :(得分:6)

只需将子列表附加到LOOP

CL-USER 23 > (loop for l in '((SHAPE BRICK) (COLOR GREEN) (SIZE SMALL)
                              (SUPPORTED-BY B2) (SUPPORTED-BY B3))
                   append l)
(SHAPE BRICK COLOR GREEN SIZE SMALL SUPPORTED-BY B2 SUPPORTED-BY B3)

或使用REDUCEAPPEND

CL-USER 24 > (reduce #'append
                     '((SHAPE BRICK) (COLOR GREEN) (SIZE SMALL)
                       (SUPPORTED-BY B2) (SUPPORTED-BY B3)))
(SHAPE BRICK COLOR GREEN SIZE SMALL SUPPORTED-BY B2 SUPPORTED-BY B3)

或使用MAPCAN

CL-USER 25 > (mapcan #'copy-list
                     '((SHAPE BRICK) (COLOR GREEN) (SIZE SMALL)
                       (SUPPORTED-BY B2) (SUPPORTED-BY B3)))
(SHAPE BRICK COLOR GREEN SIZE SMALL SUPPORTED-BY B2 SUPPORTED-BY B3)

MAPCAN 映射列表中的函数并破坏性地连接结果列表。因此,使用COPY-LIST复制子列表。