泛型
OCaml 里用以下方式使用泛型
1 | type f = a Template |
Lists
构造列表有三种语法
1 | [] (* 空列表 *) |
列表的基础操作:
1 | lst1 @ lst2 (* 列表拼接 *) |
Pattern Matching
1 | (* 用 match with 进行 pattern matching,注意必须涵盖所有可能的情况 *) |
如果 pattern matching 的对象是最后一个参数,那么我们可以用 function 语法糖
1 | let rec sum lst = |
Variants
A variant is a data type representing a value that is one of several possibilities. 类似其他语言里的 enum
1 | type day = Sun | Mon | Tue | Wed | Thu | Fri | Sat |
后定义的 variant 如果有相同的名字,那么会产生覆盖,所以建议在定义 variant 的时候,带上独特的前缀.
1 | type t1 = C | D |
使用 OUnit 进行单元测试
OUnit 进行单元测试假设 sum.ml 里面定义了函数
1 | let rec sum = function |
我们创建一个 test.ml 进行单元测试
1 | open OUnit2 |
在项目的 dune 文件里对 test.ml 添加编译
1 | (executable |
运行
1 | dune exec ./text.exe |
现在我们来看看 OUnit 如何定义单元测试.
1 | [ |
然后,我们创建 test suite:
1 | let tests = "test suite for sum" >::: [ |
>::: 放在 test suite 和 a list of unit tests 之间.
最后运行测试:let _ = run_test_tt_main tests
在匿名函数中添加 ~printer 参数可以打印 first argument 和 second argument.
Records
我们还是用 type 关键字定义有字段的结构体,字段之间用 ; 分隔.
1 | type ptype = TNormal | TFire | TWater |
Record Copy
1 | (* |
Tuples
1 | (* 用逗号分隔进行定义,同样可以 pattern matching *) |
Type Synonyms
已有类型的别名,还是用 type 进行定义
1 | type point = float * float |
Options
和 Haskell 的 Maybe 是类似的生态位
1 | let extract o = |