2012-04-24 73 views
5

是否有可能通過將其數據綁定到單個值而不是元組來解壓類型?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

[使用只有一個元組值的變體類型構造函數]可能的重複(http://stackoverflow.com/questions/9774671/using-a-variant-type-constructor-with-just-one-tuple-value ) – ygrek 2012-04-25 07:48:58

回答

9

這是OCaml語法的一個棘手部分。如果在顯示時定義類型,則其構造函數Foo需要括號中的兩個值。它總是有兩個值,它不是一個單一的值,而是一個元組。

如果你願意使用不同的類型,你可以做更多的東西一樣,你想要什麼:

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

當宣佈這種方式,構造Bar預計一個值,這是一個元組。這可以更加靈活,但它也需要更多的內存來表示它,而訪問這些部分需要更長的時間。