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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
type 'a t = 'a option
let use (o:'a t) (b:'b) (f:'a -> 'b): 'b =
match o with
| None -> b
| Some a -> f a
let fold (none:'z) (some:'a -> 'z): 'a t -> 'z = function
| None -> none
| Some a -> some a
let return (a:'a): 'a t =
Some a
let (>>=) (m:'a t) (f:'a -> 'b t): 'b t =
match m with
| None -> None
| Some a -> f a
let map (f:'a -> 'b) (o:'a t): 'b t =
match o with
| None -> None
| Some a -> Some (f a)
let (>=>) (f:'a -> 'b t) (g:'b -> 'c t) (a:'a): 'c t =
f a >>= g
let (<*>) (fo: ('a -> 'b) t) (o:'a t): 'b t =
fo >>= fun f -> map f o
let join (oo:'a option option): 'a option =
match oo with
| None -> None
| Some o -> o
let to_list (o: 'a t): 'a list =
match o with
| None ->
[]
| Some v ->
[v]
let has (o: 'a t): bool =
match o with
| None -> false
| Some _ -> true
let value (o: 'a t): 'a =
match o with
| None ->
assert false
| Some x ->
x
let of_bool (b:bool): unit t =
if b then
Some ()
else
None
let iter (f:'a -> unit) (m:'a t): unit =
ignore (map f m)
let fold_interval (f:'a->int->'a t) (a0:'a) (start:int) (beyond:int): 'a t =
assert (start <= beyond);
let rec fold i a =
if i = beyond then
Some a
else
match f a i with
| None ->
None
| Some a ->
fold (i+1) a
in
fold start a0
let fold_array (f:'a->'b->int->'a t) (start:'a) (arr:'b array): 'a t =
let len = Array.length arr
in
let rec fold a i =
if i = len then
Some a
else
match f a arr.(i) i with
| Some a ->
fold a (i+1)
| None ->
None
in
fold start 0