Two fields of two records have same label in OCaml
Asked Answered
C

3

12

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.

Cuculiform answered 19/1, 2012 at 15:46 Comment(2)
Update: since OCaml version 4.01.0 the requirement for unique record field labels is removed.Bergstein
@Bergstein I think that is only true if the names have different types, which does not apply here.Brigham
R
16

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.

Roswell answered 19/1, 2012 at 16:35 Comment(1)
Maybe you can add a link to the FAQ: caml.inria.fr/pub/old_caml_site/FAQ/…Gonorrhea
M
8

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.

Miller answered 19/1, 2012 at 15:49 Comment(3)
Thanks for your comment... Why do you think it is better to have a suffix like _t for type names?Cuculiform
Just a question of readability. I feel that dtype sounds like some value (e.g. some function).Miller
@BasileStarynkevitch seeing as type and value contexts are always known, surely there's no ambiguity?Thacker
S
1

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
Stevenage answered 15/3, 2018 at 19:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.