OCaml构造函数解压缩 [英] OCaml constructor unpacking
问题描述
是否可以通过将类型的数据绑定到单个值而不是元组来解压缩类型?
Is it possible to unpack a type by binding its data to a single value instead of a tuple?
# 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"
这在语法上可行吗?
推荐答案
这是OCaml语法的棘手部分.如果按显示方式定义类型,则其构造函数Foo
会在括号中包含两个值.而且它始终必须是两个值,而不是一个元组的单个值.
This is a tricky part of OCaml syntax. If you define your type as you show, its constructor Foo
expects two values in parentheses. And it always has to be two values, it's not a single value that's a tuple.
如果您愿意使用其他类型,则可以做更多您想做的事情:
If you're willing to use a different type, you can do something more like what you want:
# 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
期望一个元组的 one 值.这样可以更加灵活,但也需要更多的内存来表示它,并且需要更长的时间来访问零件.
When declared this way, the constructor Bar
expects one value that's a tuple. This can be more flexible, but it also takes a little more memory to represent it, and a little longer to access the parts.
这篇关于OCaml构造函数解压缩的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!