2009-12-20 148 views
9

在OCaml的语言规范,有短款:什么是ocaml类型'a。 'a - >'是什么意思?

poly-typexpr ::= typexpr 
       | { ' ident }+ . typexpr 

有没有在文本没有解释,并poly-typexpr的唯一实例是定义一个方法类型:

method-type ::= method-name : poly-typexpr 

这说明什么允许我做什么?

回答

12

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