I noticed this semi weirdish-behavior in one of my projects using Scheme and lists. I managed to isolate the behavior into a single section. The code is:
(define x (list 1 2 3)) (define y (list 4 5)) (define z (cons (car x) (cdr y))) (define w (append y z)) (define v (cons (cdr x) (cdr y))) (set-car! x 6) (set-car! y 7) (set-cdr! (cdr x) (list 8)) x y z w v
Gives us the output of:
(6 2 8) (7 5) (1 5) (4 5 1 5) ((2 8) 5)
Can anyone explain to me:
- Why does
(set-car! x 6)not updateZ? Since according to my understandingcar/cdrreturn pointers or references to the corresponding values. This is really weird and I’m kinda confused. - If
car/cdrdoes not return references/pointers then how is the finalset-cdr!manipulating the listv?
Any ideas? It’s a simple fix, but I’m more curious as to why the weirdness with the variables is going on.
Okay, let’s step through your program line by line. I’m also assigning unique numbers (think of them as object addresses, if you’re used to C-like languages) for each newly-created object so you can see what’s what. 🙂
Now, let’s look at your values (for each reference, use the last assigned value):
Edit: I’m adding a diagram to explain my answer, since you can’t have diagrams in a comment. I don’t have time to make a diagram showing the values above, but this hopefully explains a few things.
Each pair has two ‘slots’,
carandcdr, represented as the left and right boxes in the diagram above. Each of these slots, as you see, has three possible things:let,s5, andsqrt)You can put any of these in any of the slots. So, in my explanation above, each of the
#items is an arrow, each of the non-#numbers is an atom, and each of the()is a black box. So, in the lineyou are creating a pair, where the left-hand slot has the same contents as the right-hand slot of
x(i.e., an arrow going to pair 2), and the right-hand slot has the same contents as the right-hand slot ofy(an arrow going to pair 5). In other words, both boxes invcontain arrows, each going off a different pair.Hope this makes more sense. 🙂