我刚刚在OCaml关于GADTs的文档中发现了以下代码片段:
let rec eval : type a. a term -> a = function
| Int n -> n
| Add -> (fun x y -> x + y)
| App (f, x) -> (eval f) (eval x)
在utop中评估后,其签名如下:
val eval : 'a term -> 'a = <fun>
我还注意到,当用
'a term -> 'a
替换type a. a term -> a
或仅删除签名时,该函数将无法编译。...
| Add -> (fun x y -> x + y)
...
Error: This pattern matches values of type (int -> int -> int) term
but a pattern was expected which matches values of type int term
Type int -> int -> int is not compatible with type int
那么这个符号是什么?它与'a t
有何不同之处?
它是否专门针对GADTs?
'a .
的用法(参见手册中的7.12节)。类型系统不会将let f (x:'a) : 'a = x + 1
视为错误,因为int
可以统一。而type a
创建了一个局部抽象类型。在GADTs中,每个分支都可以实例化为不同的类型,例如示例Antoine
中的a
。在希望在多态函数中使用具体类型的情况下,这允许引用该类型。 - nlucaronitype a. ...
这个语法要求a
是可以多态的。它由'a. ...
(用于强制多态性)和(type a)
(声明一个局部抽象类型)组合而成。 - Leo Whitetype a.
的展开方式。而'a
语法则在https://ocamlverse.github.io/content/weak_type_variables.html中有详细说明。 - Max Heiber