Page 1 of 1
novice question about CONS
Posted: Sun Apr 12, 2009 7:01 am
by whiteman
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
Posted: Mon Apr 13, 2009 10:20 am
by findinglisp
Use recursion. Check out IF or COND and ATOM.
Re: novice question about CONS
Posted: Mon Apr 13, 2009 2:10 pm
by Jasper
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
Posted: Mon Apr 13, 2009 5:10 pm
by methusala
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)))))
Re: novice question about CONS
Posted: Sun Apr 26, 2009 9:59 pm
by jrigler
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)
Re: novice question about CONS
Posted: Mon Apr 27, 2009 9:42 am
by Tom
This was also discussed in another thread.
viewtopic.php?f=2&t=268&start=0