Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

lisp: consolidate a list-of-lists into a single list?

Tags:

list

lisp

Still working on lisp recipes and idioms.

I have a list like this:

((a b c) (d e f) nil (g h))

I'd like to consolidate that to one list,

(a b c d e f g h)

Seems like there oughta be a one-liner for that.

like image 981
Cheeso Avatar asked Apr 11 '10 18:04

Cheeso


2 Answers

(apply #'append '((a b c) (d e f) (g h i)))

or

(loop for outer in '((a b c) (d e f) (g h i))
      nconcing (loop for inner in outer collecting inner))
like image 166
Dirk Avatar answered Nov 01 '22 19:11

Dirk


That's a typical homework question. Generally this operation is called FLATTEN (which flattens lists on all levels).

(mapcan #'copy-list '((a b c) (d e f) nil (g h)))

The APPLY variant has the problem that it may run into the CALL-ARGUMENTS-LIMIT when there are more sublists than CALL-ARGUMENTS-LIMIT.

See for example also http://rosettacode.org/wiki/Flatten_a_list#Common_Lisp

like image 29
Rainer Joswig Avatar answered Nov 01 '22 19:11

Rainer Joswig