【发布时间】:2022-01-18 15:41:47
【问题描述】:
我遇到了一个记录被赋予弱多态类型的情况,我不知道为什么。
这是一个最小化的例子
module type S = sig
type 'a t
val default : 'a t
end
module F (M : S) = struct
type 'a record = { x : 'a M.t; n : int }
let f = { x = M.default; n = (fun x -> x) 3 }
end
这里f 的类型是'_weak1 record。
有(至少)两种方法可以解决这个问题。
- 第一个包括为函数应用程序使用辅助定义。
let n = (fun x -> x) 3 let f = { x = M.default; n } - 第二个是将
t的类型参数声明为协变。module type S = sig type +'a t val default : 'a t end
我觉得奇怪的是函数应用程序用于初始化类型为int 的字段,它与类型为t 的类型变量'a 完全没有链接。而且我也不明白为什么将'a 声明为协变突然允许在这个不相关的字段中使用任意表达式而不会丢失多态性。
【问题讨论】:
标签: ocaml