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.)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| ;; 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) |