package hardcaml_event_driven_sim

  1. Overview
  2. Docs

Source file mini_async.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
open Base

module Deferred_basic = struct
  type 'a t_val =
    | Filled of 'a
    | Waiting of ('a -> unit) list

  type 'a t = 'a t_val ref

  let upon t f =
    match !t with
    | Filled value -> f value
    | Waiting callbacks -> t := Waiting (f :: callbacks)
  ;;

  let return value = ref (Filled value)

  let peek t =
    match !t with
    | Filled value -> Some value
    | Waiting _ -> None
  ;;

  module Ivar = struct
    type nonrec 'a t = 'a t

    let read t = t

    let fill t value =
      match !t with
      | Filled _ -> failwith "attempting to fill Ivar which is already filled"
      | Waiting callbacks ->
        t := Filled value;
        List.iter callbacks ~f:(fun f -> f value)
    ;;

    let is_filled t =
      match !t with
      | Filled _ -> true
      | Waiting _ -> false
    ;;

    let create () = ref (Waiting [])
  end

  let bind t ~f =
    let result = Ivar.create () in
    upon t (fun a -> upon (f a) (fun b -> Ivar.fill result b));
    result
  ;;

  let map =
    `Custom
      (fun t ~f ->
        let result = Ivar.create () in
        upon t (fun a -> Ivar.fill result (f a));
        result)
  ;;

  let unit = return ()
end

module Deferred = struct
  include Deferred_basic
  include Monad.Make (Deferred_basic)
end

module Let_syntax = Deferred.Let_syntax
module Ivar = Deferred_basic.Ivar
OCaml

Innovation. Community. Security.