gpt4 book ai didi

ocaml - 在 OCaml 中简化后无法解构产品类型

转载 作者:行者123 更新时间:2023-12-02 02:18:21 24 4
gpt4 key购买 nike

我在 OCaml 中有这个简单的代码:

type int_pair = int * int;;
type a = A of int_pair;;
let extract (A x) = x;;

测试我的extract 函数,它似乎有效:

# extract (A (1,2));;
- : int_pair = (1, 2)

我简化了它,所以它只需要一种类型:

type a' = A' of int * int;;
let extract' (A' x) = x;;

但我收到错误:

Error: The constructor A' expects 2 argument(s),
but is applied here to 1 argument(s)

有趣的是,我可以构造 a' 的值...

# A' (1,2);;
- : a' = A' (1, 2)

...我就是无法解构它们。为什么?

最佳答案

您需要使用

type a' = A' of (int * int)

这是 OCaml 类型规范中棘手的地方之一。

涉及两种略有不同的不同类型:

type one_field = F1 of (int * int)
type two_fields = F2 of int * int

one_field 类型中,有一个字段是一对整数。在 two_fields 类型中,有两个字段,每个字段都是 int。棘手的是构造函数看起来相同:

# F1 (3, 5);;
- : one_field = F1 (3, 5)
# F2 (3, 5);;
- : two_fields = F2 (3, 5)

这两种类型是不同的,并且实际上在内存中的表示方式不同。 (两个字段的变体实际上占用的空间更少,并且访问速度稍快。)

关于ocaml - 在 OCaml 中简化后无法解构产品类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15752651/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com