Two fields from two records have the same label in OCaml

I defined two types of records:

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 an error later for the 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

Can someone tell me if we should not have two fields from two records with the same label, for example typ , which makes the compiler get confused.

+8
types record ocaml
source share
2 answers

No, you cannot, because it will violate type inference.

btw, you can use the module namespace to fix this:

 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 with the correct module:

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

Note that you only need the prefix of only the first field, and the compiler will automatically understand what type of value you write has.

+13
source share

Ocaml language requires that all fields inside the module have different names. Otherwise, it will not be able to infer the type of the function below.

 let get_typ r = r.typ ;; 

since it can be of type name -> dtype or of type func -> dtype

By the way, I suggest you have a _t type suffix for all your type names.

+8
source share

All Articles