Blame


1 665c255d 2023-08-04 jrmu ;; 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.
2 665c255d 2023-08-04 jrmu
3 665c255d 2023-08-04 jrmu (define (cycle? l)
4 665c255d 2023-08-04 jrmu (let ((traversed '()))
5 665c255d 2023-08-04 jrmu (define (not-all-unique? l)
6 665c255d 2023-08-04 jrmu (cond ((not (pair? l)) #f)
7 665c255d 2023-08-04 jrmu ((memq l traversed) #t)
8 665c255d 2023-08-04 jrmu (else (set! traversed (cons l traversed))
9 665c255d 2023-08-04 jrmu (not-all-unique? (cdr l)))))
10 665c255d 2023-08-04 jrmu (not-all-unique? l)))
11 665c255d 2023-08-04 jrmu
12 665c255d 2023-08-04 jrmu (define (test-case actual expected)
13 665c255d 2023-08-04 jrmu (newline)
14 665c255d 2023-08-04 jrmu (display "Actual: ")
15 665c255d 2023-08-04 jrmu (display actual)
16 665c255d 2023-08-04 jrmu (newline)
17 665c255d 2023-08-04 jrmu (display "Expected: ")
18 665c255d 2023-08-04 jrmu (display expected)
19 665c255d 2023-08-04 jrmu (newline))
20 665c255d 2023-08-04 jrmu
21 665c255d 2023-08-04 jrmu (define (last-pair x)
22 665c255d 2023-08-04 jrmu (if (null? (cdr x))
23 665c255d 2023-08-04 jrmu x
24 665c255d 2023-08-04 jrmu (last-pair (cdr x))))
25 665c255d 2023-08-04 jrmu
26 665c255d 2023-08-04 jrmu (define (make-cycle x)
27 665c255d 2023-08-04 jrmu (set-cdr! (last-pair x) x)
28 665c255d 2023-08-04 jrmu x)
29 665c255d 2023-08-04 jrmu
30 665c255d 2023-08-04 jrmu (define three '(a b c))
31 665c255d 2023-08-04 jrmu (define a-pair (cons '() '()))
32 665c255d 2023-08-04 jrmu (define b-pair (cons a-pair a-pair))
33 665c255d 2023-08-04 jrmu (define four (cons 'a b-pair))
34 665c255d 2023-08-04 jrmu (define seven (cons b-pair b-pair))
35 665c255d 2023-08-04 jrmu (define circular (make-cycle '(a b c)))
36 665c255d 2023-08-04 jrmu
37 665c255d 2023-08-04 jrmu (test-case (cycle? three) #f)
38 665c255d 2023-08-04 jrmu (test-case (cycle? four) #f)
39 665c255d 2023-08-04 jrmu (test-case (cycle? seven) #f)
40 665c255d 2023-08-04 jrmu (test-case (cycle? circular) #t)