Two fields of two records have same label in OCaml

坚强是说给别人听的谎言 提交于 2019-12-30 17:26:14

问题


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 }

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

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


回答1:


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.




回答2:


The Ocaml language requires all fields inside a module to have different names. Otherwise, it won't be able to infer the type of the below function

let get_typ r = r.typ ;;

because it could be of type name -> dtype or of type func -> dtype

BTW, I suggest you to have a suffix like _t for all your type names.




回答3:


You can use type annotation in function signature when compiler failed to infer the type from the duplicate record label. For example,

let get_name_type (n:name) = n.typ

let get_func_type (f:func) = f.typ


来源:https://stackoverflow.com/questions/8928970/two-fields-of-two-records-have-same-label-in-ocaml

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