-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathgeneric_util_option.ml
More file actions
54 lines (44 loc) · 1.36 KB
/
Copy pathgeneric_util_option.ml
File metadata and controls
54 lines (44 loc) · 1.36 KB
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
(** Operations on option types. *)
open Generic_util
(** [option f] is the functorial action of the functor ['a option]:
{[Some x -> Some (f x)]}
{[None -> None]}
*)
let option f = function
| Some x -> Some (f x)
| None -> None
let map = option
let functorial = Functor.option
(** [unopt s n] eliminates an option value by replacing the constructor [Some] by [s] and [None] by [n].
*)
let unopt n s = function
| None -> n
| Some x -> s x
(** Partial function {[get_some (Some x) = x]}
@raise Failed on None
*)
let get_some = function
| Some x -> x
| None -> raise Exn.Failed
(** [opt_try x] forces the lazy value [x]. If any exception is raised,
[None] is returned, otherwise [Some x] is returned.
*)
let opt_try x =
let debug = false in (* during development it may be useful to display the exception *)
if debug then Some (Lazy.force x)
else
try Some (Lazy.force x)
with _ -> None
(** [some_if f x = Some x] if [f x] is true, [None] otherwise *)
let some_if f x =
if f x then Some x else None
(** [unopt_try s n x = unopt s n (opt_try x)] *)
let unopt_try n s x =
unopt n s (opt_try x)
(** Monadic plus, the left argument has priority on the right
in case both options have a value. *)
let leftist_plus x y = match x, y with
| Some _ , _ -> x
| None , Some _ -> y
| None , None -> None
let to_list = function None -> [] | Some x -> [x]