Subject: Re: [Q] More beginner help
From: Erik Naggum <>
Date: 2000/01/24
Newsgroups: comp.lang.lisp
Message-ID: <>

[ please look at how other Common Lisp programmers indent and present their
  code.  parentheses are _not_ visually significant, although they are very
  syntactically significant, in Lisp source code.  don't make them stand
  out -- please -- you're code is so ugly it's hard to help you with it. ]

* Dirt <>
| I am trying to "unravel" a list, but with little luck. I wish to take a
| list such as:
| 	(a (b c (d e)) f)
| and create a new list that looks like one top level list:
| 	(a b c d e f)

  this is normally called "flattening" a list.

| I am trying to do this recursively but I am guessing I am way off because
| I get a stack overflow.  What I am trying to say in my code below is:
| If the expression is a list, call the function again with the cdr of the
| list, otherwise it is an atom so cons it to a list.

  what you wish to do is to move each element of each list you encounter
  onto a new list.  I'll try to show you with slightly more modern Common
  Lisp that you're using:

(defun flatten (list)
  (loop for element in list
        if (listp element) nconc (flatten element)
        else collect element))

  if you actually _need_ recursion, which will only waste space and time,
  you should be able to unravel this iterative solution easily.  in my not
  so humble opinion, being able to think recursively is very valuable, the
  second most valuable ability you can have, beaten only by knowing _when_
  to use recursion.

  incidentally, this function considers an empty list a list of no elements
  while you might want NIL to be a separate element in the resulting list.