Ocaml Lwt型混乱

问题描述 投票:0回答:1

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

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

ocaml utop ocaml-lwt
1个回答
2
投票

我怀疑你因为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。这是(>>=)的第一个参数,因此'aunit(>>=)的第二个参数是ff采取unit,这是我们需要的,因为'aunit。它返回一个unit Lwt.t,所以'b也是unit。这意味着最终结果将是unit Lwt.t

© www.soinside.com 2019 - 2024. All rights reserved.