1
0
Fork 0

SICP 05: 代码清单

This commit is contained in:
Darcy Shen 2024-03-13 22:01:27 +08:00
parent d88c911ec0
commit b9db91859c
2 changed files with 134 additions and 3 deletions

131
SICP/code05.tm Normal file
View File

@ -0,0 +1,131 @@
<TeXmacs|2.1.2>
<style|<tuple|generic|no-page-numbers|british|reduced-margins>>
<\body>
<section*|Orders of Growth>
<\session|scheme|default>
<\unfolded-io|Scheme] >
(define (expt-1 b n)
\ \ (if (= n 0)
\ \ \ \ \ \ 1
\ \ \ \ \ \ (* b (expt-1 b (- n 1)))))
<|unfolded-io>
expt-1
</unfolded-io>
<\unfolded-io|Scheme] >
(expt-1 1 0)
<|unfolded-io>
1
</unfolded-io>
<\unfolded-io|Scheme] >
(expt-1 2 3)
<|unfolded-io>
8
</unfolded-io>
<\unfolded-io|Scheme] >
(define (expt-2 b n)
\ \ (define (expt-iter b counter product)
\ \ \ \ (if (= counter 0)
\ \ \ \ \ \ \ \ product
\ \ \ \ \ \ \ \ (expt-iter b
\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ (- counter 1)
\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ (* b product))))
\ \
\ \ (expt-iter b n 1))
<|unfolded-io>
expt-2
</unfolded-io>
<\unfolded-io|Scheme] >
(expt-2 3 3)
<|unfolded-io>
27
</unfolded-io>
<\input|Scheme] >
\;
</input>
</session>
<section*|Exponentiation>
<\session|scheme|default>
<\unfolded-io|Scheme] >
(define (fast-expt b n)
\ \ (define (even? n)
\ \ \ \ (= (remainder n 2) 0))
\ \ (define (square x) (* x x))
\ \
\ \ (cond ((= n 0) 1)
\ \ \ \ \ \ \ \ ((even? n) (square (fast-expt b (/ n 2))))
\ \ \ \ \ \ \ \ (else (* b (fast-expt b (- n 1))))))
<|unfolded-io>
fast-expt
</unfolded-io>
<\unfolded-io|Scheme] >
(fast-expt 3 3)
<|unfolded-io>
27
</unfolded-io>
</session>
<section*|Greatest Common Divisors>
<\session|scheme|default>
<\unfolded-io|Scheme] >
(define (gcd a b)
\ \ (if (= b 0)
\ \ \ \ \ \ a
\ \ \ \ \ \ (gcd b (remainder a b))))
<|unfolded-io>
gcd
</unfolded-io>
<\unfolded-io|Scheme] >
(gcd 10 20)
<|unfolded-io>
10
</unfolded-io>
</session>
</body>
<\initial>
<\collection>
<associate|page-screen-margin|true>
</collection>
</initial>
<\references>
<\collection>
<associate|auto-1|<tuple|?|?>>
<associate|auto-2|<tuple|?|?>>
<associate|auto-3|<tuple|?|?>>
</collection>
</references>

View File

@ -24,13 +24,13 @@
<item>\<#76EE\>\<#6807\>\<#90AE\>\<#7BB1\>\<#FF1A\>shenda AT ustc.edu
</itemize>
<item>\<#7B2C\>5\<#8BFE\>\<#FF1A\>\<#7B97\>\<#6CD5\>\<#7684\>\<#65F6\>\<#95F4\>\<#590D\>\<#6742\>\<#5EA6\>
<item>\<#7B2C\>5\<#8BFE\>\<#FF1A\>\<#7B97\>\<#6CD5\>\<#7684\>\<#65F6\>\<#7A7A\>\<#590D\>\<#6742\>\<#5EA6\>
\<#8BB2\>\<#4E49\>\<#FF1A\>\<#4EA4\>\<#4E92\>\<#5F0F\>\<#8BB2\>\<#4E49\>05
\<#8BB2\>\<#4E49\>\<#FF1A\><hlink|\<#4EA4\>\<#4E92\>\<#5F0F\>\<#8BB2\>\<#4E49\>05|https://gitee.com/XmacsLabs/interactive-sicp/raw/main/course05.tm>
\<#8BFE\>\<#4EF6\>\<#FF1A\>\<#5E7B\>\<#706F\>\<#7247\>05
\<#4EE3\>\<#7801\>\<#FF1A\>\<#4EE3\>\<#7801\>\<#6E05\>\<#5355\>05
\<#4EE3\>\<#7801\>\<#FF1A\><hlink|\<#4EE3\>\<#7801\>\<#6E05\>\<#5355\>05|code05.tm>
<item>\<#7B2C\>4\<#8BFE\>\<#FF1A\>\<#9012\>\<#5F52\>\<#4E0E\>\<#8FED\>\<#4EE3\>\<#FF08\>\<#4E60\>\<#9898\>\<#8BFE\>\<#FF09\>