How do I use a type that is mimicing another type?

I have

type typeVar = int;;

How do I create an instance/value of it?

When you define a type without constructors, you are defining a synonym for the type. That is, you’re not defining a new type. So all int values are instances of your type typeVar.

Example:

# type typeVar = int;;
type typeVar = int
# let x = (4 : typeVar);;
val x : typeVar = 4
2 Likes

so I can’t construct elements of my “new” type?

(I added an example to my answer.)

1 Like

Note that OCaml provides a way to expose a type as int while preventing you from constructing values of such type. I invite you to try this:

module ID : sig
  (** The type of a unique ID. *)
  type t = private int

  (** Create a unique ID *)
  val create : unit -> t
end = struct
  type t = int
  let counter = ref 0
  let create () =
    let id = !counter in
    incr counter;
    if !counter = 0 then
      failwith "too many IDs";
    id
end

You can then create a unique ID and still use it as an int:

let id = ID.create ()
let () = print_int (id :> int)
1 Like

I dont think I understand the syntax for me to understand the example unfortunately :frowning:

The first part sig ... end is what you would have in a .mli file. It’s the interface of a module. The second part within struct ... end is the implementation of the module, which would go in a .ml file. The syntax here allows you to create a submodule. I use it in the example so that you can copy-paste it in your ocaml toplevel (utop or ocaml).

The point is that we need to declare an interface in which we put type t = private int. We can’t put type t = private int in the implementation of the module (well we can, but then we can’t use it).