Skip to content

Commit 402100a

Browse files
committed
Add solution for exercise3-16
1 parent 218bac1 commit 402100a

File tree

4 files changed

+4379
-0
lines changed

4 files changed

+4379
-0
lines changed

chapter3/exercise3-16.org

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
#+LATEX_CLASS: ramsay-org-article
2+
#+LATEX_CLASS_OPTIONS: [oneside,A4paper,12pt]
3+
#+AUTHOR: Ramsay Leung
4+
5+
#+DATE: 2025-06-14 Sat 23:42
6+
7+
[[file:../img/chapter3/exercise-3-16.png]]

chapter3/exercise3-16.rkt

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
#lang racket
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+
;; 无法处理共享或循环结构
11+
(module+ test
12+
(require rackunit)
13+
14+
(test-case "Test for count-pairs return 3, without shared"
15+
(define a (list '1 '2 '3))
16+
(check-equal? (count-pairs a) 3))
17+
18+
(test-case "Test for count-pairs return 4, with shared cons"
19+
(define shared (cons 1 2))
20+
(define b (cons shared (cons shared '())))
21+
(check-equal? (count-pairs b) 4))
22+
23+
(test-case "Test for count-pairs return 7, with multiple shared cons"
24+
(define shared (cons 1 2))
25+
(define c (cons shared shared))
26+
(define d (cons c c))
27+
(check-equal? (count-pairs d) 7)
28+
)
29+
(test-case "Test for not return at all, with circular reference"
30+
;; (define cycle (cons 1 (cons 2 '())))
31+
;; (set-cdr! (cdr cycle) cycle)
32+
;; (count-pairs cycle) ; 无限循环
33+
;; racket 不支持 set-cdr!, 如果使用 =set-mcdr!= 可变的数
34+
;; 据结构, =cons=, =pair?= 都需要作出相应的修改
35+
)
36+
)
37+

0 commit comments

Comments
 (0)