-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutil_half_lazy.ml
95 lines (87 loc) · 2.12 KB
/
util_half_lazy.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
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
open Lwt
(*
Cache the result of a computation only if successful,
i.e. only when it doesn't raise an exception.
*)
let create f =
let result = ref None in
fun () ->
match !result with
| Some x -> x
| None ->
let x = f () in
result := Some x;
x
(*
Cache an asynchronous computation but only until it fails with an exception.
*)
let create_lwt f =
let in_progress = ref None in
let result = ref None in
fun () ->
match !result with
| Some ret -> ret (* cached pre-computed result *)
| None ->
match !in_progress with
| Some comp ->
(* cached computation in progress *)
comp
| None ->
(* no computation in progress *)
let comp =
catch f
(fun e -> in_progress := None; Trax.raise __LOC__ e)
in
in_progress := Some comp;
comp >>= fun _res ->
in_progress := None;
result := Some comp;
comp
let test_lwt_caching () =
Lwt_main.run (
let counter = ref 0 in
let z =
create_lwt (fun () ->
incr counter;
Lwt_unix.sleep 0.1 >>= fun () ->
return !counter
)
in
Lwt_list.map_p z [ (); (); () ] >>= fun result ->
return (result = [ 1; 1; 1 ])
)
exception Int of int
let test_lwt_exception () =
Lwt_main.run (
let counter = ref 0 in
let z =
create_lwt (fun () ->
incr counter;
Lwt_unix.sleep 0.1 >>= fun () ->
raise (Int !counter)
)
in
let wrap () =
catch
(fun () ->
z () >>= fun _ ->
assert false
)
(fun e ->
match Trax.unwrap e with
| Int n -> return n
| _ -> assert false
)
in
Lwt_list.map_p (fun f -> f ()) [ wrap; wrap ] >>= fun l ->
assert (l = [ 1; 1 ]);
assert (!counter = 1);
Lwt_list.map_s (fun f -> f ()) [ wrap; wrap ] >>= fun l ->
assert (l = [ 2; 3 ]);
assert (!counter = 3);
return true
)
let tests = [
"lwt caching", test_lwt_caching;
"lwt exception", test_lwt_exception;
]