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.

novice question about CONS

6 posts · 3509 views

Hello,

I just started lisp, and i have a question I cant resolve

how can I flatten a list like this ((1 2 3) (4 5 6) (7 8 9)) into a list ( 1 2 3 4 5 6 7 8 9) ?

cons '((1 2 3) (4 5 6) ( 7 8 9)) does not work, i guess since it takes only one argument in this case.

thanks

Re: novice question about CONS

Go over all the elements in the list.
If an element is a list, do here as described to it and append to result.(Here you recurse; you call the function itself.)
If an element is not a list just append that to the result too. (But in this case you append a single element.)

Re: novice question about CONS

If you happen to append a tree to a list, you won't flatten all the lists together, you'll get this:
(append '(1 2 (2) ) '(1 2))
(1 2 (2) 1 2)

So you need to use 'double recursion', something like this:
(defun oct (tr)
  (if (atom tr)
      (cons tr nil)
    (append (oct (car tr))
          (oct (cdr tr)))))

Re: novice question about CONS

This may be of help if you haven't seen it:

CL-USER> (concatenate 'list (list 1 2 3)(list 4 5 6)(list 7 8 9))
(1 2 3 4 5 6 7 8 9)