1. 引言
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)
这篇博客介绍了OCaml这门函数式编程语言,包括其变量的不可变性特点,如何通过`mutable`和`ref`实现变量修改,以及类型定义。此外,文章还讲解了OCaml的测试用例配置和编写方法,并提供了将Rust库封装为OCaml可调用静态库的指南。最后,讨论了如何管理和发布OCaml库到opam仓库以及指定依赖。
477

被折叠的 条评论
为什么被折叠?



