2012-04-24 74 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预计一个值,这是一个元组。这可以更加灵活,但它也需要更多的内存来表示它,而访问这些部分需要更长的时间。