This is a read-only archive of lispforum.com. The forum was locked to new users and posts and is preserved here as static HTML from a database snapshot taken on 2019-09-07.

How to remove nested parentheses in LISP

2 posts · 1730 views

I need to write a recursive function which will "collapse" a list, that is, remove all nested parentheses so that the atoms are all at the top level.
(collapse '(a b c (d e) ((f) g))) => (a b c d e f g)
(collapse '(a b)) => (a b)
(collapse '(() ((((a)))) ())) => (a)

Thanks

Re: How to remove nested parentheses in LISP

I think a better name for such a function is Flatten. I don't have a lisp implementation to test right now, but the following should work:
(defun flatten (obj)
  (if (listp obj) (mapcan #'flatten obj) (list obj)))
Here mapcan appends the list the function returns.