Chapter 3, Modularity, Objects, and State

Exercise 3.13


Clearly it creates a circle and when we call last-pair? it should get stuck in loop.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#lang sicp

(define (append! x y)
  (set-cdr! (last-pair x) y)
  x)


(define (last-pair x)
  (if (null? (cdr x))
      x
      (last-pair (cdr x))))

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

Output:

1
2
3
4
5
6
7
8
> (define z (make-cycle (list 'a 'b 'c)))
> (display z)
#0=(a b c . #0#)
> z
#0=(mcons 'a (mcons 'b (mcons 'c #0#)))
> (last-pair z)
. . user break
>