Polymorphic variant and record
「Modulaはレコードも含めて全部Structured Typeだったのに惜しい」の部分は、どうもPolymorphic recordで実現されるらしいが、よくわかりません。
http://d.hatena.ne.jp/h_sakurai/20070311
http://moscova.inria.fr/~zappa/teaching/stt05/types-3.pdf
http://caml.inria.fr/pub/docs/manual-ocaml/manual012.html
Polymorphic variantsのほうは、頭に`付ければ宣言無しでVariantが使えるとかそんならしい。
http://caml.inria.fr/pub/docs/manual-ocaml/manual006.html
# let x = ref `X;; val x : _[> `X ] ref = {contents = `X} # x := `Y;; - : unit = () # x;; - : _[> `X | `Y ] ref = {contents = `Y} # x := `Z;; - : unit = () # x;; - : _[> `X | `Y | `Z ] ref = {contents = `Z}
おー、増えていく増えていく。
なんかこれで列挙型の部分型が実現できるみたいだ。
# type color = [`Red | `Green | `Blue | `Yellow];; type color = [ `Blue | `Green | `Red | `Yellow ] # type primary_color = [`Blue | `Green | `Red];; type primary_color = [ `Blue | `Green | `Red ] # let f1 : color -> int = fun x -> Obj.magic x;; val f1 : color -> int = <fun> # let f2 : primary_color -> int = fun x -> Obj.magic x;; val f2 : primary_color -> int = <fun> # let v = `Red;; val v : [> `Red ] = `Red # f1 v;; - : int = 4100401 # f2 v;; - : int = 4100401 # let w = `Yellow;; val w : [> `Yellow ] = `Yellow # f1 w;; - : int = 82908052 # f2 w;; Characters 3-4: f2 w;; ^ This expression has type [> `Yellow ] but is here used with type primary_color The second variant type does not allow tag(s) `Yellow
……できるじゃん部分範囲型。Obj.magic後に連番にならないのが微妙に価値を落としている気がします。
結論。Obj.magicは何も思いつかないときに使える関数として大変良い。
Polymorphic recordは明日考える。