1. 引言
OCaml为函数式编程语言。
相关入门资料有:
- o1-labs的 OCaml By Examples(具体见https://github.com/o1-labs/ocamlbyexample)
- OCaml官方教程
- OCaml手册
OCaml变量与Rust类似,默认是not mutable的。如下例,是对变量 b b b的重定义。若需对同一变量值进行修改,可加“mutable”关键字,或使用引用(关键字为“ref”,引用值修改用操作符":=“),访问引用值 使用 解引用操作符”!"。而“ref”的底层本质就是a record with a mutable filed + some re-define operators to facilitate manipulation of the mutable field。
utop # let a =
let b = 5 in
let b = 5 + b in
b;;
val a : int = 10
utop # type bus = { mutable passengers : int };;
type bus = { mutable passengers : int; }
utop # let shuttle = { passengers = 0 };;
val shuttle : bus = {passengers = 0}
utop # shuttle.passengers <- 3;;
- : unit = ()
utop # shuttle;;
- : bus = {passengers = 3}
utop # let counter = ref 0;;
val counter : int ref = {contents = 0}
utop # counter := 3;;
- : unit = ()
utop # counter;;
- : int ref = {contents = 3}
utop # !counter + 4;;
- : int = 7
utop # type 'a ref = { mutable contents : 'a }
let (:=) r v = r.contents <- v
let (!) r = r.contents;;
type 'a ref = { mutable contents : 'a; }
val ( := ) : 'a ref -> 'a -> unit = <fun>
val ( ! ) : 'a ref -> 'a = <fun>
- 将Rust代码封装为静态库供OCaml调用的方法见:https://o1-labs.github.io/ocamlbyexample/libraries-rust.html
- 将所编写的OCaml库发布到opam仓库中的方法见:https://o1-labs.github.io/ocamlbyexample/build-dune-release.html
- OCaml指定特定的依赖方法见:https://o1-labs.github.io/ocamlbyexample/build-opam-pin.html
2. OCaml测试用例
OCaml测试用例以inline_tests配置,以%标记,仅能用于库中,对应dune文件配置为:
(library
(name mylib)
(libraries)
(inline_tests)
(preprocess
(pps ppx_inline_test)))
测试用例有:
let%test "some test" = true
let%test_unit "some other test" = ()
module A = struct
let lower_than_5 x = x < 5
let%test_unit _ = assert ( lower_than_5 3 )
end
let%test_module _ = (module struct
let%test _ = A.lower_than_5 8
end)