Apparently the 2 types below are different, but why ?
type 'a llist = Nil | Cons of 'a * (unit -> 'a llist)
vs
type 'a llist = Nil | Cons of ('a * unit -> 'a llist)
Doesn't Cons
take a tuple as argument in both cases ?
It's a subtle difference, but the representation is different. It can be seen on the following example:
type ta = A of int * int
type tb = B of (int * int)
A
is a constructor with two arguments, and B
is a constructor with a single tuple argument.
You can see the difference by inspecting the size of the objects at runtime:
let size x =
Obj.size (Obj.repr x)
let () = Printf.printf "%d %d\n" (size (A (2, 3))) (size (B (2, 3)))
This will display "2 1" - in the second case, only a pointer to the tuple is stored, and the tuple is stored in another block.
This also means that you can manipulate the tuple itself:
let get_a (A x) = x (* error: The constructor A expects 2 argument(s),
but is applied here to 1 argument(s) *)
let get_b (B x) = x (* works *)
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