Oleg
Oleg

Reputation: 1559

Ocaml tuple type missunderstanding

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 ?

Upvotes: 4

Views: 518

Answers (1)

Étienne Millon
Étienne Millon

Reputation: 3028

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 *)

Upvotes: 10

Related Questions