Version française
Home     About     Download     Resources     Contact us    
Browse thread
Compiler feature - useful or not?
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Virgile Prevosto <virgile.prevosto@m...>
Subject: Re: [Caml-list] Compiler feature - useful or not?
Le mer 14 nov 2007 13:37:24 CET,
Alain Frisch <alain@frisch.fr> a écrit :

> Pierre Weis wrote:
> > type row = private int;;
> 
> The only difference with an abstract type is that some generic 
> operations (comparision, equality) can be optimized, and currently,
> it happens only for some basic types. So exporting a private
> abbreviation (instead of an abstract type) is useless when the type
> is not a basic type. Is it correct?
> 

As far as I understand Pierre's original email, this is not simply
about optimization (which is in fact a simple by-product of the
feature). The main point of private is to distinguish between the
construction of a value (where you might want to enforce some invariant)
and its use (where you might rely on the invariant). You can use a
value of type row everywhere a plain int is expected (in particular for
addition, subtraction, etc.), without having to redefine the
corresponding functions as would have been necessary with an abstract
type. On the other hand, the construction of a value of type row from a
plain int is impossible outside of the constructor function provided in
the module, which checks that the invariant required for row is
satisfied. This can be useful for other types as well, consider for
instance the following module (not tested of course)

module Sorted:
sig
type sorted_list = private int list
val empty: sorted_list
val insert: int -> sorted_list -> sorted_list
end = 
struct
type sorted_list = int list
let empty = []
let rec insert x = function 
 [] -> [x] 
| y::_ as l when x < y -> x::l
| y::l -> y :: insert x l
end

A value of type Sorted.sorted_list is a list, for which all operations
of module List are available (as well as pattern-matching), but in
addition it is guaranteed that a sorted_list is sorted, since it must
be built with empty and insert.

-- 
E tutto per oggi, a la prossima volta.
Virgile