LoginSignup
5
4

More than 5 years have passed since last update.

OCaml 4.01.0 から、異なるレコード型で同一のフィールド名を持つことができるようになった

Last updated at Posted at 2014-10-13

これまでは、あるレコード型のフィールド名は、スコープ内でユニークなものでなければならなかったけど、OCaml 4.01.0 からは、異なる型で同一のフィールド名を持つことができるようになったようだ。

It is now possible to have several variant constructors or record fields of the same name in scope, and type information will be used to disambiguate which one is used -- instead of always using the last one.

(* $ ocaml -w +41 # warning 41, disabled by default,
                   # warns when the last-in-scope is used without type information *)
# type t = A | B;;
# type u = A;;
# let x : t = A;;
val x : t = A
# let y = A;;
Warning 41: A belongs to several types: u t
The first one was selected. Please disambiguate if this is wrong.
val y : u = A

This slightly controversial feature can be tweaked in various ways through an extensive set of warning (40, 41, 42): by converting some of them as errors, you can disable it completely or control its applicability. See http://www.lexifi.com/blog/type-based-selection-label-and-constructors for a more detailed description of the feature.

From [Caml-announce] OCaml release 4.01.0

実際に試してみる。

(*    OCaml version 4.01.0      *)

(* 同一名のフィールドを持つ、異なる二つのレコード型を定義 *)
# type student = { name : string; id : int };;
type student = { name : string; id : int; }
# type foo = { name : string };;
type foo = { name : string; }

(* 問題なく foo 型も student 型も作成できている *)
# { name = "Harou" };;
- : foo = {name = "Harou"}
# { name = "Test"; id = 22 };;
- : student = {name = "Test"; id = 22}

(* 同じフィールド名の組み合わせを持った場合は既存の型が上書きされてしまうようだ *)
# type hoge = { name : string; id : string };;
type hoge = { name : string; id : string; }
# { name = "Test"; id = 22 };;
Characters 22-24:
  { name = "Test"; id = 22 };;
                        ^^
Error: This expression has type int but an expression was expected of type string

# type student = { name : string; id : int };;
type student = { name : string; id : int; }
# type hoge = { name : string; id : int };;
type hoge = { name : string; id : int; }
# { name = "Test"; id = 22 };;
- : hoge = {name = "Test"; id = 22}
5
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
4