Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two fields of two records have same label in 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 }

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.

like image 926
SoftTimur Avatar asked Jan 19 '12 15:01

SoftTimur


3 Answers

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.

like image 114
Thomas Avatar answered Nov 15 '22 17:11

Thomas


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
like image 27
Mianyu Wang Avatar answered Nov 15 '22 19:11

Mianyu Wang


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.

like image 25
Basile Starynkevitch Avatar answered Nov 15 '22 17:11

Basile Starynkevitch