How to remove nested parentheses in LISP

Discussion of Common Lisp
Post Reply
orcik1
Posts: 2
Joined: Tue Apr 20, 2010 7:48 pm

How to remove nested parentheses in LISP

Post by orcik1 » Tue Apr 20, 2010 7:52 pm

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

Jasper
Posts: 209
Joined: Fri Oct 10, 2008 8:22 am
Location: Eindhoven, The Netherlands
Contact:

Re: How to remove nested parentheses in LISP

Post by Jasper » Wed Apr 21, 2010 4:10 am

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.

Post Reply