-
Notifications
You must be signed in to change notification settings - Fork 40
Expand file tree
/
Copy pathchapter7.ml
More file actions
428 lines (331 loc) · 11.8 KB
/
chapter7.ml
File metadata and controls
428 lines (331 loc) · 11.8 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
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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
(********************************************************************
* exercise: promise and resolve
********************************************************************)
module type Promise = sig
type 'a state = Pending | Fulfilled of 'a | Rejected of exn
type 'a promise
type 'a resolver
(** [make ()] is a new promise and resolver. The promise is pending. *)
val make : unit -> 'a promise * 'a resolver
(** [return x] is a new promise that is already fulfilled with value [x]. *)
val return : 'a -> 'a promise
(** [state p] is the state of the promise *)
val state : 'a promise -> 'a state
(** [resolve r x] fulfills the promise [p] associated with [r]
with value [x], meaning that [state p] will become
[Fulfilled x].
Requires: [p] is pending. *)
val resolve : 'a resolver -> 'a -> unit
(** [reject r x] rejects the promise [p] associated with [r]
with exception [x], meaning that [state p] will become
[Rejected x].
Requires: [p] is pending. *)
val reject : 'a resolver -> exn -> unit
(** [p >>= c] registers callback [c] with promise [p].
When the promise is fulfilled, the callback will be run
on the promises's contents. If the promise is never
fulfilled, the callback will never run. *)
val bind : 'a promise -> ('a -> 'b promise) -> 'b promise
end
module Promise : Promise = struct
type 'a state = Pending | Fulfilled of 'a | Rejected of exn
(* RI: if [state <> Pending] then [callbacks = []]. *)
type 'a promise = {
mutable state : 'a state;
mutable callbacks : ('a -> unit) list
}
type 'a resolver = 'a promise
(** [write_once p s] changes the state of [p] to be [s]. If [p] and [s]
are both pending, that has no effect.
Raises: [Invalid_arg] if the state of [p] is not pending. *)
let write_once p s =
if p.state = Pending
then p.state <- s
else invalid_arg "cannot write twice"
let make () =
let p = {state = Pending; callbacks = []} in
p, p
let return x =
{state = Fulfilled x; callbacks = []}
let state p = p.state
let reject r x =
write_once r (Rejected x);
r.callbacks <- []
let run_callbacks callbacks x =
List.iter (fun f -> f x) callbacks
let resolve r x =
write_once r (Fulfilled x);
let callbacks = r.callbacks in
r.callbacks <- [];
run_callbacks callbacks x
let bind (p : 'a promise) (c : 'a -> 'b promise) : 'b promise =
match p.state with
| Fulfilled x -> c x
| Rejected x -> {state = Rejected x; callbacks = []}
| Pending ->
let bind_promise, bind_resolver = make () in
let f x : unit =
let callback_promise = c x in
match callback_promise.state with
| Fulfilled x -> resolve bind_resolver x
| Rejected x -> reject bind_resolver x
| Pending -> failwith "impossible"
in
p.callbacks <- f :: p.callbacks;
bind_promise
end
let _ =
let open Promise in
let p, r = make () in
let _ = bind p (fun i -> Printf.printf "%i\n" i; return ()) in
resolve r 42
(********************************************************************
* exercise: map via bind
********************************************************************)
module MapViaBind = struct
open Promise
let map (callback : 'a -> 'b) (input_promise : 'a promise) : 'b promise =
bind input_promise (fun x -> return (callback x))
end
(********************************************************************
* exercise: map anew
********************************************************************)
(* Note: this code would need to be inserted inside the Promise module's
implementation. *)
(* This is a lightweight version of [handler_of_callback] *)
let handler_of_callback'
(callback : 'a -> 'b)
(resolver : 'b resolver) : 'a handler
= function
| Pending -> failwith "handler RI violated"
| Rejected exc -> reject resolver exc
| Fulfilled x ->
try
let ans = callback x in
fulfill resolver ans
(* We have fewer cases to consider since the callback returns a value.
We still need a try-with block: the callback may raise an exception. *)
with exc -> reject resolver exc
let map (callback : 'a -> 'b) (input_promise : 'a promise) : 'b promise =
match input_promise.state with
| Fulfilled x -> return (callback x)
| Rejected x -> {state = Rejected x; handlers = []}
| Pending ->
let output_promise, output_resolver = make () in
enqueue (handler_of_callback' callback output_resolver) input_promise;
output_promise
module LwtExercises = struct
(********************************************************************
* exercise: promise and resolve lwt
********************************************************************)
(* to run this in utop, first [#require "lwt.unix";;] *)
let _ =
let p, r = Lwt.wait () in
let _ = bind p (fun i -> Lwt_io.printf "%i\n" i) in
Lwt.wakeup r 42
(********************************************************************
* exercise: timing challenge 1
********************************************************************)
(** [delay s] is a promise that resolves after about [s] seconds. *)
let delay (sec : float) : unit Lwt.t =
Lwt_unix.sleep sec
(** prints ["done"] after about 3 seconds. *)
let delay_then_print () =
let%lwt () = delay 3. in
Lwt_io.printl "done"
(********************************************************************
* exercise: timing challenge 2
********************************************************************)
let timing2 () =
let%lwt () = delay 1. in
let%lwt () = Lwt_io.printl "1" in
let%lwt () = delay 10. in
let%lwt () = Lwt_io.printl "2" in
let%lwt () = delay 20. in
let%lwt () = Lwt_io.printl "3" in
Lwt_io.printl "all done"
(* Answer:
- after about a second, "1" prints.
- about 10 more seconds later, "2" prints.
- about 20 more seconds later, "3" prints.
- then "all done" immediately prints.
The total elapsed time is about 31 seconds. *)
(********************************************************************
* exercise: timing challenge 3
********************************************************************)
let timing3 () =
let _t1 = let%lwt () = delay 1. in Lwt_io.printl "1" in
let _t2 = let%lwt () = delay 10. in Lwt_io.printl "2" in
let _t3 = let%lwt () = delay 20. in Lwt_io.printl "3" in
Lwt_io.printl "all done"
(* Answer:
- "all done" prints immediately.
- about a second later, "1" prints.
- about 9 more seconds later, "2" prints.
- about 10 more seconds later, "3" prints.
The total elapsed time is about 20 seconds. *)
(********************************************************************
* exercise: timing challenge 4
********************************************************************)
let timing4 () =
let t1 = let%lwt () = delay 1. in Lwt_io.printl "1" in
let t2 = let%lwt () = delay 10. in Lwt_io.printl "2" in
let t3 = let%lwt () = delay 20. in Lwt_io.printl "3" in
let%lwt () = Lwt.join [t1; t2; t3] in
Lwt_io.printl "all done"
(* Answer:
- after about a second, "1" prints.
- about 9 more seconds later, "2" prints.
- about 10 more seconds later, "3" prints.
- then "all done" immediately prints.
The total elapsed time is about 20 seconds. *)
(********************************************************************
* exercise: file monitor
********************************************************************)
open Lwt_io
open Lwt_unix
let log () : input_channel Lwt.t =
let%lwt fd = openfile "log" [O_RDONLY] 0 in
Lwt.return (of_fd input fd)
let rec loop (ic : input_channel) =
let%lwt str = read_line ic in
let%lwt () = printlf "%s" str in
loop ic
let monitor () : unit Lwt.t =
Lwt.bind (log ()) loop
let handler : exn -> unit Lwt.t = function
| End_of_file -> Lwt.return ()
| exc -> Lwt.fail exc
let main () : unit Lwt.t =
Lwt.catch monitor handler
(* uncomment to actually run the monitor:
let _ = Lwt_main.run (main ())
*)
end
(********************************************************************
* Maybe monad
********************************************************************)
module type Monad = sig
type 'a t
val return : 'a -> 'a t
val ( >>= ) : 'a t -> ('a -> 'b t) -> 'b t
end
module Maybe : Monad =
struct
type 'a t = 'a option
let return x = Some x
let ( >>= ) m f =
match m with
| Some x -> f x
| None -> None
end
open Maybe
(********************************************************************
* exercise: add opt
********************************************************************)
let add (x : int t) (y : int t) : int t =
x >>= fun a ->
y >>= fun b ->
return (a + b)
(********************************************************************
* exercise: fmap and join
********************************************************************)
module type ExtMonad = sig
type 'a t
val return : 'a -> 'a t
val ( >>= ) : 'a t -> ('a -> 'b t) -> 'b t
val ( >>| ) : 'a t -> ('a -> 'b) -> 'b t
val join : 'a t t -> 'a t
end
module Maybe : ExtMonad =
struct
type 'a t = 'a option
let return x = Some x
let ( >>= ) m f =
match m with
| Some x -> f x
| None -> None
let ( >>| ) m f =
match m with
| Some x -> Some (f x)
| None -> None
let join = function
| Some m -> m
| None -> None
end
(********************************************************************
* exercise: fmap and join again
********************************************************************)
module Maybe : ExtMonad =
struct
type 'a t = 'a option
let return x = Some x
let ( >>= ) m f =
match m with
| Some x -> f x
| None -> None
let ( >>| ) x f =
x >>= fun a ->
return (f a)
let join x =
x >>= fun y ->
y
end
(********************************************************************
* exercise: bind from fmap+join
********************************************************************)
module type FmapJoinMonad = sig
type 'a t
val ( >>| ) : 'a t -> ('a -> 'b) -> 'b t
val join : 'a t t -> 'a t
val return : 'a -> 'a t
end
module type BindMonad = sig
type 'a t
val return : 'a -> 'a t
val ( >>= ) : 'a t -> ('a -> 'b t) -> 'b t
end
module MakeMonad (M : FmapJoinMonad) : BindMonad = struct
include M
let ( >>= ) m f =
m >>| f |> join
end
(********************************************************************
* exercise: list monad
********************************************************************)
module ListMonad : ExtMonad = struct
type 'a t = 'a list
let return x =
[x]
let join =
List.flatten
let ( >>| ) m f =
List.map f m
let ( >>= ) m f =
m |> List.map f |> join
(* or, m >>| f |> join *)
end
(********************************************************************
* exercise: trivial monad laws
********************************************************************)
module Trivial : Monad = struct
type 'a t = Wrap of 'a
let return x = Wrap x
let ( >>= ) (Wrap x) f = f x
end
(*
Law 1: [return x >>= f] behaves the same as [f x].
Proof. By the definition of [return], [return x >>= f] evaluates
to [Wrap x >>= f]. By the definition of [>>=], that evaluates
to [f x].
Law 2: [m >>= return] behaves the same as [m].
Proof. Since [m : 'a t] it must be [Wrap x] for some [x]. By the
definition of [>>=], [m >>= return] thus evaluates to [return x].
By the definition of [return], that evaluates to [Wrap x],
which is just [m].
Law 3: [m >>= f >>= g] behaves the same as [m >>= (fun x -> f x >>= g)].
Proof. Since [m : 'a t] it must be [Wrap z] for some [z]. By the
definition of [>>=], [m >>= f >>= g] thus evaluates to [f z >>= g].
Likewise, [m >>= (fun x -> f x >>= g)] thus evaluates to
[(fun x -> f x >>= g) z], which evaluates to [f z >>= g].
*)