首页 > 解决方案 > 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 而不是单位。为什么调用线程的第二部分?

标签: ocamlutopocaml-lwt

解决方案


我怀疑你会因为utop聪明而感到困惑。

如果您查看utop 文档,它是这样写的

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

这就是为什么

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

似乎是 type 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"因此返回 a unit Lwt.t。这是 的第一个参数(>>=)'a因此是unit。的第二个参数(>>=)ff需要 a unit,这是我们需要的,'a就像unit. 它返回一个unit Lwt.t,所以'b也是unit。这意味着最终结果将是一个unit Lwt.t.


推荐阅读