]> git.rkrishnan.org Git - sicp.git/blob - src/sicp/ex3_16.rkt
Solutions to 4.27, 4.28 and 4.29.
[sicp.git] / src / sicp / ex3_16.rkt
1 #lang r5rs
2
3 (define (count-pairs x)
4   (if (not (pair? x))
5       0
6       (+ (count-pairs (car x))
7          (count-pairs (cdr x))
8          1)))
9
10 ;; list of exactly 3 pairs which counts as 3
11 (define z1 (cons 'a (cons 'b (cons 'c '()))))
12 (count-pairs z1)
13
14 ;; list of 3 pairs but counts as 4
15 (define x (list 'a 'b))
16 (define z2 (cons (cons 'c '()) x))
17 (count-pairs z2)
18
19 ;; list of 3 pairs but counts as 7
20 (define x3 (cons 'a 'b))
21 (define y3 (cons x3 x3))
22 (define z3 (cons y3 y3))
23 (count-pairs z3)
24
25 ;; list of 3 pairs but count never returns
26 ;;; DON'T RUN THIS. IT WILL GO INTO An INF LOOP
27 (define z4 (cons 'a (cons 'y (cons 'z '()))))
28 (define (last-pair x)
29   (if (null? (cdr x))
30       x
31       (last-pair (cdr x))))
32
33 (set-cdr! (last-pair z4) z4)
34 (count-pairs z4)