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

后端 未结 1 687
一个人的身影
一个人的身影 2021-02-02 09:46

Questions

It was my first time I saw a type definition like \'a. unit -> \'a in Explicit polymorphic type in record

Q1: What i

相关标签:
1条回答
  • 2021-02-02 10:01

    '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.

    0 讨论(0)
提交回复
热议问题