Version française
Home     About     Download     Resources     Contact us    
Browse thread
Ocaml type with constraints?
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Jacques Garrigue <garrigue@m...>
Subject: Re: [Caml-list] Ocaml type with constraints?
From: "Angela Zhu" <angela22.zhu@gmail.com>

> I want to define an OCaml type with constraints.
> For example:
> 
> type item = Item of int * float;;
> 
> If here this float type is for price of some item, and I want to make sure
> it is positive. In other words, if x = (xi, xf) of type item,
> I want to enforce, xf must >= 0.
> 
> Is there a way to define OCaml type like this?

This is the goal of private types.

module Item : sig
  type item = private Item of int * float
  val create : int -> float -> item
end = struct
  type item = Item of int * float
  let create n p =
    if p >= 0. then Item (n, p) else invalid_arg "Item.create"
end

# Item.create 3 9.95;;
- : Item.item = Item.Item (3, 9.95)
# Item.create 3 (-1.0);;
Exception: Invalid_argument "Item.create".

Note that you must imperatively use Item.create to create an item, but
you can use pattern-matching as usual to access its contents.

Jacques Garrigue