tags:

views:

324

answers:

1

The following Emacs Lisp function takes a list of lists and returns a list in which the items of the inner lists have been concatenated to one big list. It is pretty straight-forward and I am convinced something like this must already be part of the standard function library.

(defun flatten (LIST)
  (if LIST
      (append (car LIST) (flatten (cdr LIST)))
    nil))

I am looking for a function that will take a single list of lists as its argument and then append all the inner lists.

(flatten '((a b) (c d)))

will give

(a b c d)

Does anyone know whether this function is already built in, and if so, under which name?

Thanks!

+5  A: 

You're either looking for append:

(defun flatten (list-of-lists)
  (apply #'append list-of-lists))

If (and only if) you know that you'll always have a list of lists.

Otherwise:

(defun flatten (list)
  (mapcan (lambda (x) (if (listp x) x nil)) list))
Vatine
Thanks a lot for your answer, very elegant definitions. But anyway, my question was not so much for a way to achieve this behavior, but whether ELisp already provides such a function. This is really more out of curiosity, not because I'm facing a specific problem that seems very complicated...
The answer is, "yes, it does", namely mapcan over the identity function.
jrockway
I don't think so: mapcan takes two arguments (the identity function and a list) while the suspected "flatten" takes only a list. (Where is Curry when you need him?) Anyway, as I said before, it's not really important, and vatine's solutions above are both great.