-
Notifications
You must be signed in to change notification settings - Fork 0
/
reference_test.ml
61 lines (41 loc) · 1.11 KB
/
reference_test.ml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
(*
定义 引用变量
*)
let a = ref 0;;
(* 类型为: val a : int ref = {contents = 0} *)
(* 赋值 *)
a := 5;;
(* 读取 *)
let b = !a;;
(* 可更改的记录分量 *)
type myPen {
mutable color : myColor;
mutable width : int;
}
(* 定义颜色枚举 *)
type myColor = Red | Blue | Green | Yollow | Purple | Pink
(* 实例化一只画笔 *)
let mPen : myPen = {
color = Red;
width = 1;
};;
(* 修改画笔颜色 *)
mPen.color <- Yollow;;
(* 一个函数 两个 显示类型的 入参 *)
let color_change (pen : myPen) (color : myColor) =
pen.color <- color;;
(* 调用 *)
color_change mPen Purple;;
(* 数组 *)
let arr = [|1; 3; 5; 7|] ;;
(* 类型: val arr : int array = [|1; 3; 5; 7|] *)
(* 使用 *)
let ele = arr.(2);;
arr.(2) <- 8;;
(* 一个函数 *)
let arr_get (arr : 'a array) (i : int) =
try
arr.(i)
with Invalid_argument _ ->
let err = Printf.sprintf "Array access at %i is invalid" i in failwith err;; (* failwith 为 抛出一个异常 关键字 *)
(* 类型: val arr_get : 'a array -> int -> 'a = <fun> *)