您当前的位置: 首页 > 

mutourend

暂无认证

  • 1浏览

    0关注

    661博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

OCaml入门

mutourend 发布时间:2022-03-10 18:42:45 ,浏览量:1

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  unit = 
val ( ! ) : 'a ref -> 'a = 
  • 将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)
关注
打赏
1664532908
查看更多评论
立即登录/注册

微信扫码登录

0.0375s