F# 學習筆記 5 等位和記錄
2013-03-11
// 型別: 等位
// ---------------------------------------------------------------
type Expr =
| Num of int
| Add of Expr * Expr
| Mul of Expr * Expr
| Var of string
let rec Evaluate (env:Map<string int="">) exp =
match exp with
| Num n -> n
| Add (x, y) -> Evaluate env x + Evaluate env y
| Mul (x, y) -> Evaluate env x * Evaluate env y
| Var id -> env.[id]
let environment = Map.ofList [ "a", 1 ;
"b", 2 ;
"c", 3 ]
// Create an expression tree that represents
// the expression: a + 2 * b.
let expressionTree1 = Add(Variable "a", Multiply(Number 2, Variable "b"))
// Evaluate the expression a + 2 * b, given the
// table of values for the variables.
let result = Evaluate environment expressionTree1
</string>
有心要學好它就一口氣把各樣的語法都學會吧...
這回再說一個關鍵字: type type
和Java 的hashtable 一樣變成強型態了
等位的意思像其他語言的class, match 還是要存在
Num 像一個getter
Add Mul 就是function 了
expT1 是expression, 用來定義Evaluate 要做的事, 也像是一個參數的配對 整件事就是envA 放到expT1 再以Evaluate 計算, 得出resT1