jbchichoko
jbchichoko

Reputation: 1634

How to add a list in a list as an element?

For demonstration purpose,

I have list with has a list:

 > (setf x (list '(1 2 1) '(4 5 4)))
 ((1 2 1) (4 5 4))
 > (length x)
 2

I want to add a new list '(2 3 2) to it. The append function:

 > (append '(2 3 2) x)
 (2 3 2 (1 2 1) (4 5 4))

 > (length (append '(2 3 2) x))
 5

isn't really doing what I want.

What I want is to add '(2 3 2) like this:

((8 7 8) (1 2 1) (4 5 4))

so that the length is 3.

So far, I haven't seen any example or ways to do what I want. Is there a built-in function or effective way of doing this ?

Upvotes: 1

Views: 198

Answers (2)

Rainer Joswig
Rainer Joswig

Reputation: 139261

APPEND appends lists. If you have a list of two sublists ((1 2 1) (4 5 4)) and you want to append another list of one sublist ((2 3 2)) in front of it.

CL-USER 99 > (append '((2 3 2)) '((1 2 1) (4 5 4)))
((2 3 2) (1 2 1) (4 5 4))

or use this, if you want to add one item in front of the list:

CL-USER 98 > (cons '(2 3 2) '((1 2 1) (4 5 4)))
((2 3 2) (1 2 1) (4 5 4))

Upvotes: 2

Paul Nathan
Paul Nathan

Reputation: 40309

APPEND is not a destructive function, which is what you are asking for. What APPEND does is allocate a new list, which it then returns.

What you can do to achieve your goals is:

(setf x (append '((...)) x)) ;;appends the quoted list to x

There is also the function NCONC, which adjusts pointers destructively.

For your meditations, I present example work:

CL-USER> (defparameter *x* nil)
*X*
CL-USER> (setf *x* '((1 2 3) (4 5 6)))
((1 2 3) (4 5 6))
CL-USER> (append *x* '(10 11 12))
((1 2 3) (4 5 6) 10 11 12)
CL-USER> (append *x* '((10 11 12)))
((1 2 3) (4 5 6) (10 11 12))
CL-USER> (setf *x* (append *x* '((10 11 12))))
((1 2 3) (4 5 6) (10 11 12))
CL-USER> *x*
((1 2 3) (4 5 6) (10 11 12))
CL-USER> 

Upvotes: 4

Related Questions