Are basic elements really indispensable? How to express and use an object's internal state can follow different ideas. Readers can treat this as several ways of writing the same character — just clarify the logical concepts it contains.
car and cdr are the way scheme organizes data structures, used together with cons:
1 2 3 4 5 6 7 8
(car (cons1234)) ; => 12 (cdr (cons1234)) ;=> 34
; after introducing assignment operations ; set-car! can change the first item; set-cdr! can change the second (define y (cons1234)) (set-car! y 56) (car y) ; 56
It’s scheme’s built-in way, but of course we can implement it ourselves. SICP actually introduces several schemes; I’ve organized them to share with everyone.
Before Introducing Assignment – cons That Is Never Modified After Creation
Defining the allocator, SICP P152
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
(define (cons x y) (define (dispatch m) (cond ((= m 0) x) ((= m 1) y) (else (error"Argument not 0 or 1: CONS" m)) ) ) dispatch )
(define (car z) (z0)) (define (cdr z) (z1))
(car (cons1234)) (cdr (cons1234))
Using lambda, SICP P153
A scheme proposed by the logician Alonzo Church. The main idea: cons doesn’t exist in isolation — cons is only meaningful when paired with car and cdr,
so there’s no need to give cons’s full implementation; it only needs to serve as input data for the subsequent selectors.
1 2 3 4 5 6 7 8 9 10 11 12
(define (cons a b) (lambda (f) (f a b)) ) (define (car c) (c (lambda (a b) a)) ) (define (cdr c) (c (lambda (a b) b)) )
(car (cons1234)) (cdr (cons1234))
After Introducing Assignment – the Corresponding Data Can Be Modified
Equivalent to adding set-car and set-cdr functions.
(define (cons a b) (define (sa x) (set! a x)) (define (sb x) (set! b x)) (lambda (f) (f a b sa sb)) ) (define (car c) (c (lambda (a b sa sb) a)) ) (define (cdr c) (c (lambda (a b sa sb) b)) ) (define (set-car c new-a) (c (lambda (a b sa sb) (sa new-a))) )
(define (set-cdr c b) (c (lambda (a b sa sb) (sb new-a))) )
(define y (cons1234)) (set-car y 56) (car y) (cdr y)
Summary
Before and after introducing assignment actually correspond to different ways we view the world. Before assignment, for a given function,
its input and output can remain consistent; after introducing assignment, functions or other structures have internal state,
becoming independent individuals. I suggest watching section 9 — assignment, state and side effects — which reminded me of function reentrancy.