Nazariy
Nazariy

Reputation: 727

Merge list of lists and return in a loop

I am trying to merge all list of lists into one.

Here is my code so far:

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

The function (DESC2 BLOCK) returns the following:

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

I simply need the function to return a merged list:

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

I have tried so many ways and have researched so much. I am sorry, but I don't fully know the LISP language, and would appreciate it if you can help me!

Thank You in advance!

Upvotes: 0

Views: 97

Answers (1)

Rainer Joswig
Rainer Joswig

Reputation: 139311

Just append the sublists in a 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)

or use REDUCE to APPEND

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)

or use 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 maps a function over a list and concatenates the result lists destructively. Thus use COPY-LIST to copy the sub lists.

Upvotes: 6

Related Questions