List and Aggregate Procedures

Create pairs, read list and vector elements, change vectors, and find the argument errors for each procedure.

Use these procedures to create pairs, read list or vector elements, and change a vector in place. The tables show the required arguments, returned values, and errors.

Read an element

Paste each example into the playground and run it.

LISPEX
(list (list-ref (list 10 20 30) 1) (vector-ref #(4 5) 0))

Result

OUTPUT
(20 4)

Indices start at zero. list-ref reads the second list element, 20. vector-ref reads the first vector element, 4.

Pairs, vectors, strings, and bytevectors are called aggregate values because they hold other values, characters, or bytes.

Change a vector

LISPEX
(define v (vector 4 5))
(define same v)
(vector-set! v 0 9)
(list (vector-ref same 0) (eq? v same))

Result

OUTPUT
(9 #t)

vector-set! replaces the first element of v. The change is also visible through same, which refers to that vector. The vector keeps its object identity, so eq? returns #t.

vector-set! returns zero values. The example reads the vector afterward to show the change.

Create a mutable vector with vector or vector-copy. Literal vectors such as #(4 5) and quoted vectors are immutable. Trying to change them produces E312. Pairs and bytevectors are also immutable in the current language profile.

Calls and errors

Here, k is an exact integer index starting at zero. A proper list is a chain of pairs ending in the empty list (), or the empty list itself.

CallResultInvalid arguments
(cons a d)a new pair containing a and daccepts any two values
(car pair) / (cdr pair)the stored first / second partE310 if the argument is not a pair
(list-ref proper-list k)the element at index kE312 if the list is not proper or k is not an exact integer; E311 if k is out of range
(vector-ref vector k)the element at index kE312 for a wrong type; E311 for an out-of-range index
(vector-set! vector k value)zero values; changes the existing vectorE312 for a wrong type or immutable vector; E311 for an out-of-range index
(bytevector-u8-ref bytevector k)an exact integer from 0 to 255E312 for a wrong type; E311 for an out-of-range index

The error depends on the procedure. For example, car reports E310 for a non-pair, while list-ref reports E312 for an improper list.

Other operations

TaskProcedures
create lists and pairslist, make-list, cons
read partscar, cdr, their combinations such as cadr, list-ref, list-tail
searchmember, memv, memq, assoc, assv, assq
copy, join, or reverse listslist-copy, append, reverse
create, copy, or transform vectorsvector, make-vector, vector-copy, vector-map

Data and aggregate types explains value shapes. Equality and object identity explains comparisons. The procedure index lists the other procedure families.