OCaml入门

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>

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)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值