-
Notifications
You must be signed in to change notification settings - Fork 10
/
ex-3.18.scm
39 lines (32 loc) · 845 Bytes
/
ex-3.18.scm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
;;; 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.
; With set!.
(define (circular? x)
(define visited '())
(define (go x)
(if (pair? x)
(if (memq x visited)
#t
(begin
(set! visited (cons x visited))
(go (cdr x))))
#f))
(go x))
; Without set!.
(define (circular? x)
(let go ([x x]
[visited '()])
(if (pair? x)
(if (memq x visited)
#t
(go (cdr x) (cons x visited)))
#f)))
(load "./sec-3.3-sample-lists.scm")
(define (check x)
(print (zap x) " ==> " (circular? x)))
(check z3)
(check z4)
(check z7)
(check z*)