8

我在 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)

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

4

1 回答 1

14

你需要使用

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)

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

于 2013-04-01T22:14:09.900 回答