In OCaml, what type definition is this: 'a. unit -> 'a

烂漫一生 提交于 2019-12-02 22:26:17

'a. means "for all types 'a". The OCaml top-level usually doesn't bother showing it, which is why it doesn't appear in the output. Any expression printed that contains type variables has an implicit forall at the start unless shown elsewhere.

When defining a function, it can be useful to add this at the start to ensure the type is polymorphic. e.g.

# let f : ('a -> 'a) = fun x -> x + 1;;
val f : int -> int = <fun>

Here, the 'a -> 'a just constrains the function's output type to be the same as its input type, but OCaml is free to limit it further. With the 'a., this doesn't happen:

# let f : 'a. ('a -> 'a) = fun x -> x + 1;;
Error: This definition has type int -> int which is less general than
     'a. 'a -> 'a

You need to specify the 'a. when defining record or object types and you want to scope the type variable to an individual member rather than to the whole object.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!