How to make a covariant observable in OCaml

霸气de小男生 提交于 2019-12-05 18:23:38

You can shift the place of capture:

module Thing :
  sig
    type +'a t
    val make : 'a -> 'a t
    val watch : ('a -> unit) -> 'a t -> unit
    val notify : 'a t -> unit
  end = struct
    type 'a t = {
      obj : 'a;
      watch : ('a -> unit) -> unit;
      notify : unit -> unit;
    }

    let make x =
      let queue = Queue.create () in
      let obj = x in
      let watch f = Queue.add f queue in
      let notify () = Queue.iter (fun f -> f x) queue in
      { obj; watch; notify; }

    let watch fn x = x.watch fn
    let notify x = x.notify ()
  end

If you want to feel really economical:

    let make x =
      let queue = Queue.create () in
      let obj = x in
      let rec watch f = Queue.add f queue
      and notify () = Queue.iter (fun f -> f x) queue in
      { obj; watch; notify; }
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!