Version française
Home     About     Download     Resources     Contact us    
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 Rajchenbach-Teller <David.Teller@u...>
Subject: Re: [Caml-list] define incompatible type
     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.

   type user_id = User of int
   type movie_id = Movie of int

   let a = User 57 and b = Movie 80 in
   if a = b then ...

This is the technique often used by Haskellites. Variant on the topic: use singleton records instead of singleton sums.


The second one is to make use of modules and abstract types, e.g.

  module User =
  struct
     type id = int
     let id_of_int x = x
   ...
  end :
  sig
     type id (*Abstract type*)
     val id_of_int : int -> id
  end
  (*same for b*)
  let a = User.id_of_int 57 and b = User.id_of_int 80 in
  if a = b then ...

 This is probably the most common technique in OCaml, as it fits well with functorization.


Finally, you can use a phantom type, e.g.

  type 'a id = {id: int} (*Type argument used only to differentiate between various kinds of ids*)
  type user                 (*This type has no inhabitant, don't worry, it's only for coercions*)
  type movie              (*same here*)

  let a = {id:57} : user id and b = {id:80}: movie id in
  if a = b then ...

It's an elegant technique, which I personally like, but which can sometimes cause puzzling error messages if you forget coercions.


I hope this helps,
 Regards,
  David


On Feb 12, 2010, at 7:32 AM, Grégoire Seux wrote:

> hello !
> 
> i would like to create two types and use the type checker to verify the "meaning" of my programs:
> 
> type user_id = int
> type movie_id = int
> 
> i'd like if the type checker would warn me if i write something that is non-sense:
> let a:user_id = 57 and b:movie_id = 80 in
> if a=b then ...
>  
> because this is obvioulsy a mistake
> 
> do you know if is this possible ?
> thanks by advance !
> 
> 
> -- 
> Grégoire
> _______________________________________________
> Caml-list mailing list. Subscription management:
> http://yquem.inria.fr/cgi-bin/mailman/listinfo/caml-list
> Archives: http://caml.inria.fr
> Beginner's list: http://groups.yahoo.com/group/ocaml_beginners
> Bug reports: http://caml.inria.fr/bin/caml-bugs