Skip to content

Commit 541bc60

Browse files
committed
Add implementation of exercise 3-55 and 3-56
1 parent 65d6ac3 commit 541bc60

File tree

4 files changed

+49
-2
lines changed

4 files changed

+49
-2
lines changed

README.org

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@
2525
习题完成情况:
2626
- 章节一: 43/46
2727
- 章节二: 88/97
28-
- 章节三: 55/82
28+
- 章节三: 57/82
2929
- 章节四: TODO
3030
- 章节五: TODO
3131
* 运行

chapter3/exercise3-56.rkt

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
#lang racket
2+
(require "stream.rkt")
3+
(require "infinite-stream.rkt")
4+
5+
;;; 合并排序
6+
(define (merge s1 s2)
7+
(cond ((stream-null? s1) s2)
8+
((stream-null? s2) s1)
9+
(else
10+
(let ((s1car (stream-car s1))
11+
(s2car (stream-car s2)))
12+
(cond ((< s1car s2car)
13+
(cons-stream s1car (merge (stream-cdr s1) s2)))
14+
((< s2car s1car)
15+
(cons-stream s2car (merge s1 (stream-cdr s2))))
16+
(else
17+
;; s1car = s2car
18+
(cons-stream s1car
19+
(merge (stream-cdr s1)
20+
(stream-cdr s2)))))))))
21+
22+
(define S (cons-stream 1 (merge (scale-stream S 2) (merge (scale-stream S 3) (scale-stream S 5)))))
23+
(module+ test
24+
(require rackunit)
25+
26+
(test-case "Test for merge"
27+
(define s1 (list-to-stream '(1 2 3 5 7)))
28+
(define s2 (list-to-stream '(2 4 5 8 9)))
29+
(define s3 (merge s1 s2))
30+
(check-equal? (stream-to-list s3 10) '(1 2 3 4 5 7 8 9))
31+
)
32+
(test-case "Test for S"
33+
(check-equal? (stream-to-list S 20) '(1 2 3 4 5 6 8 9 10 12 15 16 18 20 24 25 27 30 32 36))
34+
)
35+
)

chapter3/exercise3-57.org

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
#+LATEX_CLASS: ramsay-org-article
2+
#+LATEX_CLASS_OPTIONS: [oneside,A4paper,12pt]
3+
#+AUTHOR: Ramsay Leung
4+
5+
#+DATE: 2025-07-28 Mon 21:32
6+
7+
使用 memoization 的做法相当于保证 =fib(k)= 每个数 =k= 只会被计算一次,这个就是动态规划的雏形了。
8+
9+
如果不加 memo,时间复杂度就会变成 =2^n=,有大量的数被重复计算了。

chapter3/infinite-stream.rkt

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,10 @@
2626
(define (add-streams s1 s2)
2727
(map-stream + s1 s2))
2828

29-
(provide add-streams ones integers fibs)
29+
(define (scale-stream stream factor)
30+
(stream-map (lambda (x) (* x factor)) stream))
31+
32+
(provide add-streams scale-stream ones integers fibs)
3033

3134
(module+ test
3235
(require rackunit)

0 commit comments

Comments
 (0)