programming-languages学习笔记--第2部分

programming-languages学习笔记–第2部分

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

val a_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的值,需要:

  1. 检查是哪个构造器构造的
  2. 提取数据

例如: 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));

Author: ntestoc

扫描二维码关注公众号,回复: 4315877 查看本文章

Created: 2018-12-01 Sat 12:42

猜你喜欢

转载自www.cnblogs.com/ntestoc/p/10048927.html
今日推荐