Next: , Previous: , Up: Sequence Functions   [Index]


E.3.5 Modifying Existing List Structures

You can modify the CAR and CDR contents of a cons cell with the primitives ‘setcar’ and ‘setcdr’. These are destructive operations because they change existing list structure. Destructive operations should be applied only to mutable lists, that is, lists constructed via ‘cons’, ‘list’ or similar operations.

Modifying Cons Cells

Function: setcar cons object

This function stores OBJECT as the new CAR of CONS, replacing its previous CAR. In other words, it changes the CAR slot of CONS to refer to OBJECT. It returns the value OBJECT.

Function: setcdr cons object

This function stores OBJECT as the new CDR of CONS, replacing its previous CDR. In other words, it changes the CDR slot of CONS to refer to OBJECT. It returns the value OBJECT.

You can delete elements from the middle of a list by altering the CDRs of the cons cells in the list.

It is equally easy to insert a new element by changing CDRs.

Modifying Lists

Function: push element listname

This macro creates a new list whose CAR is ELEMENT and whose CDR is the list specified by LISTNAME, and saves that list in LISTNAME. In the simplest case, LISTNAME is an unquoted symbol naming a list, and this macro is equivalent to ‘(setq LISTNAME (cons ELEMENT LISTNAME))’.

‘listname’ can be a generalized variable. In that case, this macro does the equivalent of ‘(setf LISTNAME (cons ELEMENT LISTNAME))’.

See ‘pop’, which removes the first element from a list.

Function: pop listname

This macro provides a convenient way to examine the CAR of a list, and take it off the list, all at once. It removes the first element from the list, saves the CDR into LISTNAME, then returns the removed element. LISTNAME can be a generalized variable. In that case, this macro saves into LISTNAME using ‘setf’.

See setf, push.

Modifying Array Elements

Function: aset array index object

This function sets the INDEXth element of ARRAY to be OBJECT. It returns OBJECT. The ARRAY should be mutable.

Rearranging Lists

Here are some functions that rearrange lists destructively by modifying the CDRs of their component cons cells. These functions are destructive because they chew up the original lists passed to them as arguments, relinking their cons cells to form a new list that is the returned value.

Function: nconc &rest lists

This function returns a list containing all the elements of LISTS. Unlike ‘append’, the LISTS are not copied. Instead, the last CDR of each of the LISTS is changed to refer to the following list. The last of the LISTS is not altered. All arguments but the last should be mutable lists (do not use a constant list).

Function: fillarray array object

This function fills the array ARRAY with OBJECT, so that each element of ARRAY is OBJECT. It returns ARRAY.


Next: Modifying List Variables, Previous: Accessing Sequence Elements, Up: Sequence Functions   [Index]