Car installed! and enter the schema language

I am a little confused by the result of this example:

(define mk-q
  (lambda ()
    (let ([l '(x)])
      (cons l l))))


(define q (mk-q))

q
=> ((x) x)

(set-car! (cdr q) 'y)
=> ((y) y)

I wonder why both atoms xwere replaced by the procedure set-car!(my first guess is what the result would be ((x) y))?

For instance:

(define mk-q2
  (lambda ()
    (let ([l '(x)])
      (cons l (cons l l)))))

(define q2 (mk-q2))
(set-car! (cdr q2) 'y)
=> ((x) y x) which fits my understanding of set-car!

Why are both xin the first example replaced?

+5
source share
1 answer

In the first example, you have something equivalent to this:

(define cell (cons 'x null))
(define q (cons cell cell))

, cons x car, . (set-car! (cdr q) 'y), x y , . , (cons 'x null) , :

(cons (cons 'x null) (cons 'x null))
; '((x) x)

:

(cons (cons 'y null) (cons 'y null))
; '((y) y)

( (cons 'x null) , ), cons, :

(cons (cons 'x null) (cons (cons 'x null) (cons 'x null)))
; '((x) (x) x)

:

(cons (cons 'x null) (cons 'y (cons 'x null)))
; '((x) y x)

, , :

(define q2 (mk-q2))
(set-car! (cadr q2) 'y) ; notice the extra `a`
q2
=> '((y) (y) y)
+4

All Articles