两个记录的两个字段在OCaml中具有相同的标签 [英] Two fields of two records have same label in OCaml

查看:79
本文介绍了两个记录的两个字段在OCaml中具有相同的标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我定义了两种记录类型:

I have defined two record types:

type name =
    { r0: int; r1: int; c0: int; c1: int;
      typ: dtype;
      uid: uid (* key *) }

and func =
    { name: string;
      typ: dtype;
      params: var list;
      body: block }

后来我在一行代码中出错:Error: The record field label typ belongs to the type Syntax.func but is mixed here with labels of type Syntax.name

And I have got an error later for a line of code: Error: The record field label typ belongs to the type Syntax.func but is mixed here with labels of type Syntax.name

任何人都可以告诉我,我们是否不应该让两个记录的两个字段具有相同的标签,例如typ,这会使编译器产生混淆.

Could anyone tell me if we should not have two fields of two records have same label, like typ here, which makes compiler confuse.

推荐答案

不能,因为它会破坏类型推断.

No you can't because it will break type inference.

顺便说一句,您可以使用模块名称空间来解决此问题:

btw, you can use module namespace to fix that:

module Name = struct
  type t = { r0:int; ... }
end

module Func = struct
  type t = { name: string; ... }
end

然后,您可以在正确的模块前面添加字段名称:

And then later, you can prefix the field name by the right module:

let get_type r = r.Name.typ
let name = { Name.r0=1; r1=2; ... }
let f = { Func.name="foo"; typ=...; ... }

请注意,您只需要在第一个字段加上前缀,编译器就会自动了解您正在写入的值的类型.

Note that you need to prefix the first field only, and the compiler will understand automatically which type the value you are writing has.

这篇关于两个记录的两个字段在OCaml中具有相同的标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆