2012-04-24 15 views
5

タプルではなく1つの値にデータをバインドして型をアンパックすることはできますか?OCamlコンストラクタのアンパック

# type foo = Foo of int * string;; 
type foo = Foo of int * string 
# Foo (3; "bar");; 
    Foo (3; "bar");; 
Error: The constructor Foo expects 2 argument(s), 
     but is applied here to 1 argument(s) 
# Foo (3, "bar");; 
- : foo = Foo (3, "bar") 

# (* Can this possibly work? *) 
# let Foo data = Foo (3, "bar");; 
    let Foo data = Foo (3, "bar");; 
Error: The constructor Foo expects 2 argument(s), 
     but is applied here to 1 argument(s) 

# (* Here is the version that I know works: *) 
# let Foo (d1, d2) = Foo (3, "bar");; 
val d1 : int = 3 
val d2 : string = "bar" 

これは構文的に可能ですか?

+0

可能な複製[ただ1つのタプル値を持つバリアント型コンストラクタの使用](http://stackoverflow.com/questions/9774671/using-a-variant-type-constructor-with-just-one-tuple-value ) – ygrek

答えて

9

これはOCaml構文のトリッキーな部分です。表示するときに型を定義すると、そのコンストラクターFooは、かっこ内に2つの値が必要です。そして、それは常に2つの値でなければなりません。それはタプルである単一の値ではありません。

あなたが別の型を使用して喜んでいる場合、あなたはより多くのあなたが望むもののような何かを行うことができます:

# type bar = Bar of (int * string);; 
type bar = Bar of (int * string) 
# let Bar data = Bar (3, "foo");; 
val data : int * string = (3, "foo") 
# let Bar (d1, d2) = Bar (3, "foo");; 
val d1 : int = 3 
val d2 : string = "foo" 

このよう、タプルだ1つの値を期待Barコンストラクタを宣言しました。これはより柔軟にすることができますが、それを表現するために少しだけメモリを消費し、パーツにアクセスするのにもう少し時間がかかります。