<-Back

Function: Flatten

FLATTEN list

Returns a new list consisting of only the leaf-level atoms from list. Since nil is technically a list, flatten also has the effect of removing nils from list, but may be inefficient if used only for this purpose. For removing nil values from a list, consider using remove nil ... instead.

note:
from Stack Overflow forum: http://stackoverflow.com/questions/25866292/flatten-a-list-using-common-lisp
note:
Creative Commons license
 (defun flatten (lst &aux (result '()))
   (labels ((rflatten (lst1)
              (dolist (el lst1 result)
                (if (listp el)
                  (rflatten el)
                  (push el result)))))
       (nreverse (rflatten lst))))
note:
This will not work with dotted lists, only with actual lists. If you need dotted lists, use the old definition of flatten, from Paul Graham On Lisp:
  (defun flatten (tree)
   (if (atom tree)
       (ensure-list tree)
       (nconc (flatten (car tree))
              (if (cdr tree) (flatten (cdr tree))))))
arguments:
list List
see-also:
remove

<-Back