我很困惑为什么Lwt打印功能Lwt_io.print
有类型string -> unit Lwt.t
但是如果我运行Lwt_io.print "a" >>= fun () -> Lwt_io.print "b";;
结果是打印“ab”并返回类型单位。
我想这会是一个类型错误,因为Lwt_io.print返回单位Lwt.t而不是单位。为什么线程的第二部分被调用?
我怀疑你因为utop
很聪明而感到困惑。
如果你看看utop documentation,就会写出来
当使用lwt或async库时,UTop将自动等待['Lwt.t]或['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
。这是(>>=)
的第一个参数,因此'a
是unit
。 (>>=)
的第二个参数是f
。 f
采取unit
,这是我们需要的,因为'a
是unit
。它返回一个unit Lwt.t
,所以'b
也是unit
。这意味着最终结果将是unit Lwt.t
。