Version française
Home     About     Download     Resources     Contact us    

This site is updated infrequently. For up-to-date information, please visit the new OCaml website at

Browse thread
define incompatible type
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: David Allsopp <dra-news@m...>
Subject: RE: [Caml-list] define incompatible type
David Rajchenbach-Teller wrote:
>      Hi Grégoire,
> It's not directly possible in OCaml, but there are at least three methods
for doing what you
> want.
> The first one is to wrap your integers behind a constructor, e.g.


You can also use (post OCaml 3.11.0) private types if you want to be able to
use the ID values as integers but only explicitly. While I'm sure that the
ocaml compiler eliminates calls to the identity function, I like the
elegance that the conversion from id to int is a type coercion instead of a
function call. In real world uses, chances are that of_int is a useful
function doing actual work and not the identity function!

module User :
    type id = private int
    val of_int : int -> id
  end =
    type id = int
    let of_int x = x

let a = User.of_int 57
and b = User.of_int 57;;

a = b;;           (* true *)
a = 57;;          (* type error *)
(a :> int) = 57;; (* true *)