programming-languages學習筆記--第2部分
阿新 • • 發佈:2018-12-01
programming-languages學習筆記–第2部分
Table of Contents
1 自定義型別
- 基本型別 (int bool unit char)
- 複合型別 (tuples, lists, options)
構造複合型別:
- each of: 組合所有 例如:tuples
- one of: 選擇一個 例如:option
- self reference: 自引用型別,用於構造遞迴型別,例如列表和樹
list使用了全部3種構造
2 Records
record的值用欄位來儲存 record的型別也用欄位儲存 欄位的順序無關緊要 構造records: {f1 = e1, …, fn = en} 訪問 #fieldname e
與tuple相比更容易記憶(有欄位名),
3 tuples as syntactic sugar
vala_pair = (3+1, 4+2); val a_record = {second=4+2, first=3+1}; val another_pair = {2=5, 1=6}; #1 a_pair + #2 another_pair; val x = {3="hi", 1=true}; val y = {3="hi", 1=true, 2=3+2};
tuple是record的語法糖
方便設計,方便理解
4 datatype
datatypee mytype = TwoInts of int * int | Str of string | Pizza
每個mytype的值都從一個構造器產生 每個值包括:構造的tag, 對應的資料
要訪問datatype的值,需要:
- 檢查是哪個構造器構造的
- 提取資料
例如: null 和 isSome檢查 ht,tl 和 valOf 提取資料
5 case 表示式
ML使用case表示式和模式匹配訪問one-of值
datatype mytype = TwoInts of int * int | Str of string | Pizza fun f (x : mytype) = case x of Pizza => 3 | Str s => 8 | TwoInts(i1, i2) => i1 + i2 ; f Pizza; f (TwoInts (7, 9));
Created: 2018-12-01 Sat 12:42