I have this simple code in OCaml:
type int_pair = int * int;;
type a = A of int_pair;;
let extract (A x) = x;;
Testing my extract
function, it appears to work:
# extract (A (1,2));;
- : int_pair = (1, 2)
I simplify it, so it only needs one type:
type a' = A' of int * int;;
let extract' (A' x) = x;;
But I get the error:
Error: The constructor A' expects 2 argument(s),
but is applied here to 1 argument(s)
The funny thing is, I can construct values of a'
...
# A' (1,2);;
- : a' = A' (1, 2)
...I just can't deconstruct them. Why?
You need to use
type a' = A' of (int * int)
This is one of the tricky places in OCaml type specification.
There are two different types involved that are subtly different:
type one_field = F1 of (int * int)
type two_fields = F2 of int * int
In the type one_field
there's a single field that's a pair of ints. In the type two_fields
there are two fields each of which is an int. The tricky thing is that the constructor looks identical:
# F1 (3, 5);;
- : one_field = F1 (3, 5)
# F2 (3, 5);;
- : two_fields = F2 (3, 5)
These two types are distinct, and are in fact represented differently in memory. (The two-field variant actually takes less space and is slightly faster to access.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With