Coursera Programming Languages, Part A 華盛頓大學
部落格園,我又回來啦!
Static & Dynamic environment
在ML語言中,每當出現一個新的語句,我們都用現存的 Static / Dynamic Environment 對它進行 type-check / Evaluate。
只有通過 type-check 的語句才不會出現錯誤。
Value 是一種無需再進行計算處理的表達 (Expression),它 Evaluate 後的值就是它本身。
很重要的一個概念:
All the values are expressions. Not all the expressions are values.
Variable Bindings
- ML語言採用的是所謂 Binding Statement, 而不是其他語言中常見的 assignment statement。這意味著ML語言中的變數有著 immutable 的性質。
syntax:
val x = e;
Function Bindings
syntax:
fun x0(x1 : t1, x2 : t2, ..., xn : tn) = e
-
當對一個 Function binding 進行 type-checking 時,使用 current static environment 與新的
x0 : t1 * t2 * ... * tn -> t
(function type) 與x1 : t1, x2 : t2, ... xn : tn
x0 : t1 * t2 * ... * tn -> t
,而對於引數x1 : t1, ..., xn : tn
, 它們是不會新增至 top-level static environment 中的。它們只會在函式的主體中被使用。 (有點類似於函式的區域性變數?的感覺) -
對於一個 Function binding 的 evaluate 過程則比較簡單。直接將 x0 加入到 dynamic environment 中即可。這是因為 \(A function is a value.\)
-
注意到當對函式進行呼叫的時候 (function call) 時,函式 x0 已經存在於 dynamic environment 中,這使得對函式的遞迴呼叫 (recursive call) 成為可能。
Pairs and other tuples
(e1, e2) : t1 * t2
#1 pr = v1
#2 pr = v2
Tuple : 可以以有超過兩個元素的形式存在。
Lists
[e1, e2, ..., en] which all es has type t : e list
_e :: [] = [_e] (*新增*)
null [] == true
hd [1, 2, 3] = 1
tl [1, 2, 3] = [2, 3]
(*當 list 為空時,hd tl 函式丟擲異常*)
Let expressions
syntax:
let b1 b2 ... bn in e end
(*每一個 bi 都是一個 binding*)
- 建立區域性變數的重要形式。當 Let expressions 中的 bindings 同外部的變數重名時,Let expression 內部的變數會覆蓋 (shadows) 外部的變數。
- Let expression 的 type 與 e 的 type 符合
Option
ML 庫中一種特殊的資料型別專門用來處理返回為空 (NONE) 的情況。
NONE : 'a option (*空*)
SOME e : t option which e has type t
isSome a (*如果是 NONE 返回 false 否則返回 true *)
valOf a (*返回 option 型別中的值,如果是 NONE 丟擲一個異常*)
Some other expressions and operators
e1 andalso e2
e1 orelse e2
not e
e1 <> e2 (*即 e1 != e2*)
Lack of mutation and benefits thereof
ML 語言變數的 immutable 特性使得雖然存在 alias,但我們完全不用考慮其改變帶來的影響。 (C++好像也是?但 python 中的某些型別就需要考慮 alias 的影響,很煩)