简体   繁体   English

在OCaml中指定记录字段的类型

[英]Specify type of record field in OCaml

I have this code 我有这个代码

class person name_init =
  object
    val name = name_init
    method get_name = name
end;;

let p1 = new person "Steven" 
and p2 = new person "John" in
print_endline p1#get_name;
print_endline p2#get_name;;

It complains that get_name and val name in my person object are of unbound type, which I realize is accurate. 它抱怨说我的人员对象中的get_name和val名称是未绑定的类型,我知道这是准确的。 How would I specify that name_init (and therefore name and get_name) is of type string in OCaml? 如何在OCaml中指定name_init(以及name和get_name)的类型为string?

Specify parameter types for functions (including constructors) like this: 为函数(包括构造函数)指定参数类型,如下所示:

class person (name_init : string) =
…

If you have multiple parameters, put them all in the parens. 如果您有多个参数,请将它们全部放在括号中。

OCaml requires all values in the class expression to be either concrete, or bound to a type parameter. OCaml要求class表达式中的所有值都是具体的或绑定到类型参数。 As a consequence, when type system infers that the type of your expression is polymorphic you need to do something with it. 因此,当类型系统推断表达式的类型是多态的时,您需要对其进行处理。 You have two choices: 您有两种选择:

  1. Constraint expression to have specific type 约束表达式具有特定类型
  2. Constraint the expression to have type equal to the type parameters. 将表达式约束为具有等于类型参数的类型。

In the first case, the constraint can be put anywhere inside the class expression, given that this constraint will not allow the polymorphic expression to escape the class expression. 在第一种情况下,可以将约束放置在类表达式内的任何位置,因为该约束不允许多态表达式转义类表达式。 A few examples, to demonstrate the idea: 举几个例子,来说明这个想法:

Constraining at the instance variable specification: 约束实例变量规范:

class person name_init =
  object
    val name : string = name_init
    method get_name = name
end

Constraining at the method specification: 约束方法规范:

class person name_init =
  object
    val name = name_init
    method get_name : string = name
end

At your example, we have two more places where you can put the constraint, but I think that the idea is rather clear. 在您的示例中,我们还有两个地方可以放置约束,但是我认为这个想法很明确。

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

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