Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ocaml tuple type missunderstanding

Tags:

ocaml

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 ?

like image 403
Oleg Avatar asked Dec 24 '22 20:12

Oleg


1 Answers

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 *)
like image 193
Étienne Millon Avatar answered Jan 30 '23 14:01

Étienne Millon