novice question about CONS

Discussion of Common Lisp
Post Reply
whiteman

novice question about CONS

Post by whiteman » Sun Apr 12, 2009 7:01 am

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

findinglisp
Posts: 447
Joined: Sat Jun 28, 2008 7:49 am
Location: Austin, TX
Contact:

Re: novice question about CONS

Post by findinglisp » Mon Apr 13, 2009 10:20 am

Use recursion. Check out IF or COND and ATOM.
Cheers, Dave
Slowly but surely the world is finding Lisp. http://www.findinglisp.com/blog/

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

Re: novice question about CONS

Post by Jasper » Mon Apr 13, 2009 2:10 pm

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.)

methusala
Posts: 35
Joined: Fri Oct 03, 2008 6:35 pm

Re: novice question about CONS

Post by methusala » Mon Apr 13, 2009 5:10 pm

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:

Code: Select all

(defun oct (tr)
  (if (atom tr)
      (cons tr nil)
    (append (oct (car tr))
          (oct (cdr tr)))))

jrigler
Posts: 5
Joined: Tue Apr 07, 2009 11:30 am

Re: novice question about CONS

Post by jrigler » Sun Apr 26, 2009 9:59 pm

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)

Tom
Posts: 22
Joined: Sat Jun 28, 2008 12:52 pm
Location: Wichita, KS
Contact:

Re: novice question about CONS

Post by Tom » Mon Apr 27, 2009 9:42 am

This was also discussed in another thread.

viewtopic.php?f=2&t=268&start=0

Post Reply