ocaml - 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 而不是单位。为什么调用线程的第二部分?
解决方案
我怀疑你会因为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
。的第二个参数(>>=)
是f
。f
需要 a unit
,这是我们需要的,'a
就像unit
. 它返回一个unit Lwt.t
,所以'b
也是unit
。这意味着最终结果将是一个unit Lwt.t
.
推荐阅读
- curl - 如何进行 curl 发布请求并仅获取状态码作为响应?
- r - R Shiny Dashboard,更改所有超链接的颜色
- html - 滚动容器中的粘页脚取决于内容的高度
- oracle - dbms_datapump.get_dumpfile_info 在存储过程中编译时无法读取目录
- rspec - 为什么我不能在 to_raise 匹配器中捕获 Capybara::ElementNotFound ?
- python - Google Cloud Text To Speech 中的权限错误 - Python
- frontend - Apollo 客户端缓存在没有参数的嵌套对象上使用 cacheRedirects 重定向
- json - 使用正文表单数据的 nativescript 发布请求
- key - Sublime Text Key Binding - 按空格键时括号之间的应用空间
- google-api - 来自浏览器的 Google Contacts API 被 CORS 政策阻止