乐正

Actions speak louder than words.

Sicp-ex3-19

问题

重做练习3.18,采用一种只需要常量空间的算法(需要一个很聪明的想法)。

解答

练习3.19 (ex3-19.scm) download
1
2
3
4
5
6
7
8
9
10
(define (ring? x)
  (define (eq-n-times y z count)
    (cond ((<= count 0) #f)
          ((eq? y z) #t)
          (else (eq-n-times y (cdr z) (- count 1)))))
  (define (iter y count)
    (cond ((null? y) #f)
          ((eq-n-times y x count) #t)
          (else (iter (cdr y) (+ count 1)))))
  (iter x 0))

测试

1
2
3
4
5
6
7
8
9
10
11
(ring? (list 'a 'b 'c))
;Value: #f

(define x (list 'a 'b 'c))
;Value: x

(set-cdr! (last-pair x) x)
;Unspecified return value

(ring? x)
;Value: #t

draft

« sicp-ex3-18 sicp-ex3-20 »

Comments