繁体   English   中英

什么是ocaml类型'a。 'a - >'一个意思?

[英]What does the ocaml type 'a. 'a -> 'a mean?

在ocaml语言规范中,有一个简短的部分:

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

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

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

这让我能做什么?

poly-typexpr也被允许作为记录字段的类型(参见第6.8.1节 )。 这些通常被称为“存在类型”,尽管在这一点上存在一些争论 以这种方式使用多态类型会更改类型变量的范围。 例如,比较类型:

type 'a t = { f : 'a -> int; }
type u = { g : 'a. 'a -> int; }

t实际上是一个类型的家族,每个可能的值为'a 类型'at每个值必须具有类型为'a -> int的字段f 例如:

# 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是一个单一的类型。 对于任何 'a ,类型u每个值必须具有类型为'a -> int的字段g 例如:

# let z = { g = fun _ -> 0; } ;;
val z : u = {g = <fun>}

请注意, g根本不依赖于其输入的类型; 如果确实如此,则不会有'a. 'a -> int类型'a. 'a -> int '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

请参见第3.11节“多态方法” 向下滚动到“当然,约束也可能是一种显式方法类型......”

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM