`cdr`的`set-car!`也会改变`car`,为什么?

问题描述 投票:2回答:1
(define l '(a))
(define p (cons l l))
(set-car! (cdr p) 'b)

在最后一个 (set-car! (cdr p) 'b), p 将是 ((b) b) 而非 ((a) b). 为什么?

data-structures linked-list scheme mutability
1个回答
4
投票

A cons 单元格本质上包含两个 指针 到另外两个对象。你的相关代码大致可以翻译成这个伪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
© www.soinside.com 2019 - 2024. All rights reserved.