novice question about CONS
novice question about CONS
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
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
-
- Posts: 447
- Joined: Sat Jun 28, 2008 7:49 am
- Location: Austin, TX
- Contact:
Re: novice question about CONS
Use recursion. Check out IF or COND and ATOM.
Cheers, Dave
Slowly but surely the world is finding Lisp. http://www.findinglisp.com/blog/
Slowly but surely the world is finding Lisp. http://www.findinglisp.com/blog/
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.)
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:
(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
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)
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
Thomas M. Hermann
Odonata Research LLC
http://www.odonata-research.com/
http://www.linkedin.com/in/thomasmhermann
Odonata Research LLC
http://www.odonata-research.com/
http://www.linkedin.com/in/thomasmhermann