2013-04-01 43 views
8

簡化後,我在OCaml的這個簡單的代碼:無法解構產品類型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) 

...我只是不能解構它們。爲什麼?

回答

13

您需要使用

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) 

這兩種類型是不同的,並且事實上在內存中代表不同。 (兩場變體實際佔用的空間較小,訪問速度稍快。)