forked from ocaml-multicore/effects-examples
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathref.ml
More file actions
69 lines (57 loc) · 1.38 KB
/
ref.ml
File metadata and controls
69 lines (57 loc) · 1.38 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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
open Printf
module type STATE = sig
type 'a t
val ref : 'a -> 'a t
val (!) : 'a t -> 'a
val (:=) : 'a t -> 'a -> unit
val run : (unit -> 'a) -> 'a
end
module State : STATE = struct
module type T = sig
type elt
effect Get : elt
effect Set : elt -> unit
end
type 'a t = (module T with type elt = 'a)
effect Ref : 'a -> 'a t
let ref v = perform (Ref v)
let (!) : type a. a t -> a =
fun (module R) -> perform R.Get
let (:=) : type a. a t -> a -> unit =
fun (module R) x -> perform (R.Set x)
let run f =
begin try
f ()
with
| effect (Ref init) k ->
(* trick to name the existential type introduced by the matching: *)
(init, k) |> fun (type a) (init, k : a * (a t, _) continuation) ->
let module R =
struct
type elt = a
effect Get : elt
effect Set : elt -> unit
end
in
init |>
begin match
continue k (module R)
with
| result -> fun x -> result
| effect R.Get k -> fun x -> continue k x x
| effect (R.Set y) k -> fun x -> continue k () y
end
end
end
open State
let foo () =
let r1 = ref "Hello" in
let r2 = ref 10 in
printf "%s\n" (!r1);
printf "%d\n" (!r2);
r1 := "World";
r2 := 20;
printf "%s\n" (!r1);
printf "%d\n" (!r2);
"Done"
let _ = run foo