OCaml构造函数解包

2024-01-08

是否可以通过将数据绑定到单个值而不是元组来解包类型?

# 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期望括号内有两个值。它总是必须是两个值,它不是一个元组的单个值。

如果您愿意使用不同的类型,您可以做一些更像您想要的事情:

# 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期望onevalue 是一个元组。这可以更灵活,但也需要更多的内存来表示它,并且访问部件的时间也更长。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

OCaml构造函数解包 的相关文章

随机推荐