Page 1 of 1

How to remove nested parentheses in LISP

Posted: Tue Apr 20, 2010 7:52 pm
by orcik1
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

Posted: Wed Apr 21, 2010 4:10 am
by Jasper
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:

Code: Select all

(defun flatten (obj)
  (if (listp obj) (mapcan #'flatten obj) (list obj)))
Here mapcan appends the list the function returns.