2
votes

I am doing exercise 3.13 from SICP but I am unsure of my answer.

Exercise 3.13: Consider the following make-cycle procedure, which uses the last-pair procedure defined in Exercise 3.12:

(define (make-cycle x) (set-cdr! (last-pair x) x) x)

Draw a box-and-pointer diagram that shows the structure z created by

(define z (make-cycle (list 'a 'b 'c)))

What happens if we try to compute (last-pair z)?

I'm trying to understand why

(last-pair z)

becomes an infinite loop. Ignoring the box-and-pointer diagram, here is how I understand it:

(set-cdr! (last-pair x) x)

(last-pair x) would be the pair (cons 'c '()), then when we do set-cdr! the pair would become:

(cons 'c (cons 'a (cons 'b (cons 'c (cons 'a (cons 'b (cons 'c (cons 'a (cons 'b (cons 'c ...))))))))))

is my understanding correct?

1

1 Answers

2
votes

No.

Your answer appears to indicate that (last-pair x) is the result of calling cons infinitely many times.

Not so.

x is still just 3 cons cells, but the last one points to the first one, creating a loop (a snake biting itself on the tail).