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.

Exercise 3.19.  Redo exercise 3.18 using an algorithm that takes only a constant amount of space. (This requires a very clever idea.)

 


;; From scheme wiki
(define (contains-cycle? lst)
(define (safe-cdr l)
(if (pair? l)
(cdr l)
'()))
(define (iter a b)
(cond
((not (pair? a)) #f)
((not (pair? b)) #f)
((eq? a b) #t)
((eq? a (safe-cdr b)) #t)
(else
(iter (safe-cdr a) (safe-cdr (safe-cdr b))))))
(iter (safe-cdr lst) (safe-cdr (safe-cdr lst))))
(define x '(1 2 3 4 5 6 7 8))
(define y '(1 2 3 4 5 6 7 8))
(set-cdr! (cdddr (cddddr y)) (cdddr y))
(define z '(1))
(contains-cycle? x)
(contains-cycle? y)

view raw

s319.scm

hosted with ❤ by GitHub

 

Discover more from Gaurav Sharma's Blog

Subscribe now to keep reading and get access to the full archive.

Continue reading