Blob


1 Exercise 3.18. Write a procedure that examines a list and determines whether it contains a cycle, that is, whether a program that tried to find the end of the list by taking successive cdrs would go into an infinite loop. Exercise 3.13 constructed such lists.
3 (define (test-case actual expected)
4 (newline)
5 (display "Actual: ")
6 (display actual)
7 (newline)
8 (display "Expected: ")
9 (display expected)
10 (newline))
12 (define (last-pair x)
13 (if (null? (cdr x))
14 x
15 (last-pair (cdr x))))
17 (define (make-cycle x)
18 (set-cdr! (last-pair x) x)
19 x)
21 (define (count-pairs x)
22 (if (not (pair? x))
23 0
24 (+ (count-pairs (car x))
25 (count-pairs (cdr x))
26 1)))
28 (define three '(a b c))
29 (define a-pair (cons '() '()))
30 (define b-pair (cons a-pair a-pair))
31 (define four (cons 'a b-pair))
32 (define seven (cons b-pair b-pair))
33 (define circular (make-cycle '(a b c)))
35 (test-case (count-pairs three) 3)
36 (test-case (count-pairs four) 4)
37 (test-case (count-pairs seven) 7)
38 (test-case (count-pairs circular) 'infinite-loop)