Ocaml Lwt类型混淆

时间:2019-04-20 00:06:55

标签: ocaml utop ocaml-lwt

我很困惑为什么Lwt打印功能Lwt_io.print具有类型 string -> unit Lwt.t 但是,如果我运行Lwt_io.print "a" >>= fun () -> Lwt_io.print "b";;,结果将打印出“ ab”并返回类型单位。

我想这将是类型错误,因为Lwt_io.print返回的单位是Lwt.t而不是单位。为什么线程的第二部分被调用?

1 个答案:

答案 0 :(得分:2)

我怀疑您因为utop很聪明而感到困惑。

如果您看到utop documentation,它会写成

  

使用lwt或异步库时,UTop将自动等待['a Lwt.t]或['a Deferred.t]值并返回['a]

这是为什么

Lwt_io.print "a" >>= fun () -> Lwt_io.print "b";;

似乎是unit类型。要查看真实类型,请尝试以下

let res = Lwt_io.print "a" >>= fun () -> Lwt_io.print "b";;
#show res;;

您将会看到,如预期的那样,unit Lwt.t

更新:

我们只是为了弄清楚类型而已

let f = fun () -> Lwt_io.print "b"
val ( >>= ) : 'a Lwt.t -> ('a -> 'b Lwt.t) -> 'b Lwt.t
val print : string -> unit Lwt.t
val f : unit -> unit Lwt.t

Lwt_io.print "a"因此返回unit Lwt.t。 这是(>>=)的第一个参数,因此'aunit(>>=)的第二个参数是ff采用unit,这正是我们需要的,因为'aunit。它返回unit Lwt.t,所以'b也是unit。这意味着最终结果将是unit Lwt.t

相关问题