2012-04-24 15 views
5

Ist es möglich, einen Typ zu entpacken, indem man seine Daten an einen einzelnen Wert anstatt an ein Tupel bindet?OCaml-Konstruktor Entpacken

# 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" 

Ist das syntaktisch möglich?

+0

mögliches Duplikat von [Verwenden eines Variant-Typkonstruktors mit nur einem Tupelwert] (http://stackoverflow.com/questions/9774671/using-a-variant-type-constructor-with-just-one-tuple-value) – ygrek

Antwort

9

Dies ist ein kniffliger Teil der OCaml-Syntax. Wenn Sie Ihren Typ so definieren, wie er angezeigt wird, erwartet sein Konstruktor Foo zwei Werte in Klammern. Und es müssen immer zwei Werte sein, es ist kein einzelner Wert, der ein Tupel ist.

Wenn Sie bereit sind, eine andere Art zu verwenden, können Sie etwas mehr tun, wie das, was Sie wollen:

# 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" 

Wenn auf diese Weise erklärt, der Konstruktor Bar erwartet ein Wert, der ein Tupel ist. Dies kann flexibler sein, erfordert aber auch etwas mehr Speicher, um es darzustellen, und ein wenig länger, um auf die Teile zuzugreifen.