Search code examples
data-structureslinked-listschememutability

`set-car!` of `cdr` changes `car` as well, why?


(define l '(a))
(define p (cons l l))
(set-car! (cdr p) 'b)

After the last (set-car! (cdr p) 'b), p will be ((b) b) rather than ((a) b). Why?


Solution

  • A cons cell essentially contains two pointers to two other objects. Your code in question would translate roughly to this pseudo-C:

    struct cons {
        void *car;
        void *cdr;
    };
    
    cons *l = &cons{"a", NULL};
    cons *p = &cons{l, l};  // no copy takes place, we're handling pointers here
    p->cdr->car = "b";  // this changes the "l" object, and nothing else