プログラミング再入門

プログラミングをもう一度ちゃんと勉強する読書ノート

SICP 1.1.2 Naming and the Environment 〜 1.1.5 The Substitution Model for Procedure Application

ノート

1.1.2 Naming and the Environment

名前付けと環境。
数値に名前をつけて計算に使う例:

> (define size 2)
> size
2
> (* 5 size)
10
> (define pi 3.14159)
> (define radius 10)
> (* pi (* radius radius))
314.159
> (define circumference (* 2 pi radius))
> circumference
62.8318
> 

It should be clear that the possibility of associating values with symbols and later retrieving them means that the interpreter must maintain some sort of memory that keeps track of the name-object pairs. This memory is called the environment

インタープリタは値に名前をつけてそれを後から参照出来る様にそれらをある種の記憶領域に保存する。この記憶領域を『環境』と呼ぶ。

1.1.3 Evaluating Combinations

式の評価。

To evaluate a combination, do the following:
1. Evaluate the subexpressions of the combination.
2. Apply the procedure that is the value of the leftmost subexpression (the operator) to the arguments that are the values of the other subexpressions (the operands).

(オペレータ、オペランド含めて)まず入れ子の式を評価して、最後に最上位のリストの評価をする。『正格』と呼ばれる評価順。オペレータもsubexpressionになるのはSchemeの特徴でCommon Lispはそうではないらしい。

式が入れ子になっていれば当然それを評価する手順には再帰的になる。

式を評価する時のルール:

  1. 数字は数値として評価される。
  2. 組み込みのオペレータはそれに対応したプログラムが実行される。
  3. それ以外は環境に登録されている名前としてその値が評価される。

defineはこのルールで評価される訳ではない。この様な式(文)をspecial formと呼ぶ。special formにはそれ用の評価ルールがある。

1.1.4 Compound Procedures

手続きの合成。

(define (square x) (* x x))

Scheme手習い』『Scheme修行』では関数の定義は必ず

(define square
  (lambda (x)
    (* x x)))

と言う形式だった。つまりdefineの後は単に名前だけが続いたが、この形式ではdefineの後に(関数名 仮引数…)と言う形式が続いている。lambdaを使った形式の省略形と解釈出来る。また、この関数を適用する時の書き方と一致するのである意味分かりやすいかも。

> (define (square x) (* x x))
> (square 21)
441
> (square (+ 2 5))
49
> (square (square 3))
81
> 

squareを使った関数sum-of-squares、および更にそれを使った関数fの例:

> (define (sum-of-squares x y)
    (+ (square x) (square y)))
> (sum-of-squares 3 4)
25
> (define (f a)
    (sum-of-squares (+ a 1) (* a 2)))
> (f 5)
136
> 
1.1.5 The Substitution Model for Procedure Application

訳すのは難しいが『代入型の手続き実行』と言った感じか。

Thus the problem reduces to the evaluation of a combination with two operands and an operator sum-of-squares.

reduceは変換あるいは分解、ここでは帰着と言っても良いかもしれない。
Substitution Modelは式を評価する過程を理解する為の簡単なモデル。実際のインタープリタの挙動とは一致しない。

Applicative order versus normal order

適用順序と正規順序。関数呼び出しを評価する方法に付いて。

  • applicative orderは適用順序と訳され引数を評価してから関数を適用する、特に引数の評価を左側から順に行う事。
  • normal orderは正規順序と訳され、引数を評価する前に関数本体を展開する非正格な評価方法。

パフォーマンスその他の理由によりLisp (Scheme)ではapplicative orderを採用しているが、normal-orderにも多いに利点がある。