在OCaml的语言规范,有短款:什么是ocaml类型'a。 'a - >'是什么意思?
poly-typexpr ::= typexpr
| { ' ident }+ . typexpr
有没有在文本没有解释,并poly-typexpr
的唯一实例是定义一个方法类型:
method-type ::= method-name : poly-typexpr
这说明什么允许我做什么?
在OCaml的语言规范,有短款:什么是ocaml类型'a。 'a - >'是什么意思?
poly-typexpr ::= typexpr
| { ' ident }+ . typexpr
有没有在文本没有解释,并poly-typexpr
的唯一实例是定义一个方法类型:
method-type ::= method-name : poly-typexpr
这说明什么允许我做什么?
poly-typexpr
也可以作为记录字段的类型(请参见Section 6.8.1)。这些通常被称为“存在类型”,尽管存在some debate on that point。以这种方式使用多态类型可以改变类型变量的范围。例如,比较类型:
type 'a t = { f : 'a -> int; }
type u = { g : 'a. 'a -> int; }
t
确实是一个类型的家庭,一个为'a
每个可能值。 'a t
类型的每个值必须具有f
的字段'a -> int
。例如:
# let x = { f = fun i -> i+1; } ;;
val x : int t = {f = <fun>}
# let y = { f = String.length; } ;;
val y : string t = {f = <fun>}
比较而言,u
是单一类型。 u
类型的每个值都必须有一个字段g
,其类型为'a -> int
,对于任意'a
。例如:
# let z = { g = fun _ -> 0; } ;;
val z : u = {g = <fun>}
请注意,g
根本不依赖于其输入的类型;如果是这样,它不会有类型'a. 'a -> int
。例如:
# let x2 = { g = fun i -> i+1; } ;;
This field value has type int -> int which is less general than 'a. 'a -> int
参见section 3.11 "Polymorphic methods"。向下滚动到“当然约束也可以是明确的方法类型...”