set-car!, set-cdr! - change the fields of a pair
(import (rnrs mutable-pairs)) ;R6RS
(import (scheme r5rs)) ;R7RS
(import (scheme base)) ;R7RS
(set-car! pair obj)
(set-cdr! pair obj)
Stores obj in the car or cdr field of pair, respectively.
- R6RS
- These procedures return unspecified values.
- R7RS
- These procedures return an unspecified value.
(define (f) (list 'not-a-constant-list))
(define (g) '(constant-list))
(set-car! (f) 3) => unspecified
(set-car! (g) 3) => unspecified
; should raise &assertion exception
(let ((x (list 'a 'b 'c 'a))
(y (list 'a 'b 'c 'a 'b 'c 'a)))
(set-cdr! (list-tail x 2) x)
(set-cdr! (list-tail y 5) y)
(list
(equal? x x)
(equal? x y)
(equal? (list x y 'a) (list y x 'b))))
=> (#t #t #f)
These procedures are used to manipulate list structures. They can be quite
confusing to use because of the normal issues caused by shared state.
In some sense, these procedures are being phased out. Racket
already uses immutable pairs, and R6RS moved these procedures to their own
library to hide them away a little bit. Modern code that needs to mutate
structures is often written with mutable records instead.
When pair is a mutable pair, these procedures behave the same in all
implementations.
This procedure can raise exceptions with the following condition types:
- &assertion (R6RS)
- The wrong number of arguments was passed or an argument was outside its
domain. In particular, this is raised if pair is not a mutable
pair.
- R7RS
- The assertions described above are errors. Implementations may signal an
error, extend the procedure's domain of definition to include such
arguments, or fail catastrophically.
R4RS, IEEE Scheme, R5RS, R6RS, R7RS
These procedures first appeared with these names in R2RS. Earlier Scheme used
the MacLisp functions rplaca and rplacd.
It is an error to mutate constants from program code, but implementations do not
have to check that this restriction is followed. Because of this, sometimes a
buggy program will work in an interpreter but fail when compiled. It is not
portable (and generally not possible) to use these procedures to create
self-modifying programs.