这是我参与11月更文挑战的第2天,活动详情查看:2021最后一次更文挑战。
带着崇敬与赞美,将本文同样献给活在计算机里的神灵。
Structure and Interpretation of Computer Programs, SCIP, 计算机程序的构造与解释。
本系列文章是 SICP 读书笔记,主要偏重整体的思考,以及 code 上的实践记录。
安装 Lisp
使用 mit 提供的 mit-scheme.
$ brew install mit-scheme
$ mit-scheme
MIT/GNU Scheme running under OS X
Type `^C' (control-C) followed by `H' to obtain information about interrupts.
Copyright (C) 2020 Massachusetts Institute of Technology
This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A
PARTICULAR PURPOSE.
Image saved on Wednesday March 10, 2021 at 2:52:49 PM
Release 11.2 || SF || LIAR/x86-64
1 ]=>
scheme 语法记录
基本表达式
1 ]=> 486
;Value: 486
1 ]=> + 1 2
;Value: #[arity-dispatched-procedure 12]
1 ]=>
;Value: 1
1 ]=>
;Value: 2
1 ]=> +
;Value: #[arity-dispatched-procedure 12]
组合式
1 ]=> (+ 1 2)
;Value: 3
1 ]=> (+ 1 2 3 4)
;Value: 10
1 ]=> (- 1 (+ (/ 1 4) (* 5 1)) 4)
;Value: -33/4
命名(第一种特殊形式)(define <name> <value>)
1 ]=> (define pi 3.14159)
;Value: pi
1 ]=> (define radius 10)
;Value: radius
1 ]=> (define circumference (* 2 pi radius))
;Value: circumference
1 ]=> circumference
;Value: 62.8318
1 ]=> (define radius 20)
;Value: radius
1 ]=> circumference
;Value: 62.8318
过程命名 (define (<func_name> <parameters>) <body>)
1 ]=> (define (square x) (* x x))
;Value: square
1 ]=>
(square 5)
;Value: 25
1 ]=> (square (square (square 5)))
;Value: 390625
1 ]=> (define (f x) (square x))
;Value: f
1 ]=> (f 5)
;Value: 25
1 ]=> (define (square x) (+ x x))
;Value: square
1 ]=> (f 5)
;Value: 10
可以看到,对于普通的命名,是直接将这个名字绑定到这个值上,并且值会预先求出来。
而对于过程命名,则是惰性求值,可以看下面这个例子:
1 ]=> (define (r x) radius)
;Value: r
1 ]=> (r 9)
;Value: 20
1 ]=> (define radius 10)
;Value: radius
1 ]=> (r 99)
;Value: 10
- 应用序:先求值参数,而后应用。(当前 lisp 使用的形式)
- 正则序:全部展开,而后求值。
比如对于 (square (+ 5 1)),应用序只需要计算一次 (+ 5 1),而正则序需要计算两次。
条件表达式与谓词
(cond (<p1> <e1>)
(<p2> <e2>)
(<p3> <e3>)
(else <ed>)
)
(if <predicate> <consequent> <alternative>)
(and <e1> ... <en>)
(or <e1> ... <en>)
(not <e>)
1 ]=> (define (abs x) (if (> x 0) x (- x)))
;Value: abs
1 ]=> (abs -5)
;Value: 5
1 ]=> (abs 5)
;Value: 5
练习
1.1
10
12
8
3
6
a
b
19
#f
4
16
6
16
1.2
(/
(+ 5 4 (- 2 (- 3 (+ 6 (/ 4 5)))))
(* 3 (- 6 2) (- 2 7))
)
;Value: -37/150