novice question about CONS

Discussion of Common Lisp

novice question about CONS

Postby 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
whiteman
 

Re: novice question about CONS

Postby 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/
findinglisp
 
Posts: 440
Joined: Sat Jun 28, 2008 7:49 am
Location: Austin, TX

Re: novice question about CONS

Postby 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.)
Jasper
 
Posts: 209
Joined: Fri Oct 10, 2008 8:22 am
Location: Eindhoven, The Netherlands

Re: novice question about CONS

Postby 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)))))
methusala
 
Posts: 35
Joined: Fri Oct 03, 2008 6:35 pm

Re: novice question about CONS

Postby 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)
jrigler
 
Posts: 5
Joined: Tue Apr 07, 2009 11:30 am

Re: novice question about CONS

Postby Tom » Mon Apr 27, 2009 9:42 am

This was also discussed in another thread.

http://www.lispforum.com/viewtopic.php?f=2&t=268&start=0
Tom
 
Posts: 22
Joined: Sat Jun 28, 2008 12:52 pm
Location: Wichita, KS


Return to Common Lisp

Who is online

Users browsing this forum: Google [Bot] and 1 guest

cron