Version française
Home     About     Download     Resources     Contact us    
Browse thread
[Caml-list] Type aliases
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Alessandro Baretta <alex@b...>
Subject: Re: [Caml-list] Type aliases


Martin Jambon wrote:

> 3) Prohibit the mixing of different types that do not derive from each
>    other, without an explicit cast:
> 
>      let my_mistake = year + month   (* Type error! *)
> 
>    where year has type year and month has type month.
>    But this could be valid:
> 
>      let some_int = (year :> int) * 13 + month
> 

When I want this kind of property I use variant tags to 
encapsulate the datum and document its semantics:

type time_value = [
| `Year of int
| `Month of int
| `Week of int
| `Day of int
| `Hour of int
| `Min of int
| `Sec of int
]


let this_year = `Year(2002)

let time_value_function = function
| `Year (y) -> ...
| `Month(m) -> ...
...

This is a fairly heavy solution in terms of code length, but 
it does guarantee type safety and excellent level of 
readability--a property you'd lose with operator overloading.

Alex

-------------------
To unsubscribe, mail caml-list-request@inria.fr Archives: http://caml.inria.fr
Bug reports: http://caml.inria.fr/bin/caml-bugs FAQ: http://caml.inria.fr/FAQ/
Beginner's list: http://groups.yahoo.com/group/ocaml_beginners