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
[Caml-list] Programming with modules
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: skaller <skaller@u...>
Subject: Re: [Caml-list] Programming with classes
On Sat, 2004-08-21 at 11:57, Jean-Baptiste Rouquier wrote:
> Quoting skaller:
> >There is a further step: constructors. Never export
> >class constructors. They must be wrapped in a normal
> >Ocaml function which returns an abstract class type.
> I would be glad to follow this rule, since I'm experiencing aesthetical problems
> with constructors (see below). But could you develop a bit on this ?

Well, I will give an 'aesthetic' argument then :)

Ocaml only allows a single constructor. Typically you'd like
to make it just establish the data of the class -- it might
not even bother checking invariants. 

However, from a usage viewpoint, you often need multiple
constructors -- for example 'empty list' and 'list of one element'
are good starting points for a list like object. Or you might
have 'make_rational(p,q)' and 'unsafe_make_rational(p,q)'
the latter assuming that p,q are relatively prime and q>0,
and the former checking q<>0 and then reducing p,q to be
relatively prime -- obviously this function is expensive
and is used when the client passes p,q -- but if you're
copying a Rational_Number object there is no need since
the invariant is already assured.

But one can go further and say that, well, anything which
creates an object is a constructor. For example if you 
concantenate two 'list like objects' to get 'list like object'
is not that function a constructor? It is, after all, making
a new object.

So it seems sensible to 'abstract' the notion of 'user accessible
constructor' away from the physical constructor and make the
physical type constructor as brain dead and efficient
as possible, the price being it is unsafe: we protect against
that by restricting access to it.

> My problem is that I'm exporting many class constructors (if you explain me why
> I shouldnt, the next version probably won't) 

There is a trade off, obviously: abstraction costs.

One argument against exporting actual constructors is that
it makes your code fragile. It is hard to change the
representation of a type, when the constructor often
needs representation dependent data as arguments.

John Skaller,
voice: 061-2-9660-0850, 
snail: PO BOX 401 Glebe NSW 2037 Australia
Checkout the Felix programming language

To unsubscribe, mail Archives:
Bug reports: FAQ:
Beginner's list: