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 ocaml.org.

Browse thread
class virtual vs class type?
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: 2002-05-02 (21:01)
From: Remi VANICAT <vanicat+egroups@l...>
Subject: Re: "ocaml_beginners"::[] class virtual vs class type?
"bwv211mail" <bwv211mail@y...> writes:

> A couple of questions about classes:
> 
> (1) What is the difference between a class with all virtual methods
> and a class type? Are they interchangeable?


There is little difference between the two. you can inherit from one,
not from the others. but as you can do a 

class ['a] bar =
object(_: 'a #foo)
...

and you will have exactly the same things.

But inheritance is the traditional way of having this.

> 
> (2) Also, why are classes often declared with a unit parameter when
> they appear to be constant? For example, in the new Ocaml book p.472
> they write:
> 
> class virtual ['a] o_list () =
> object
> method virtual empty : unit -> head
> method virtual cons : 'a -> 'a o_list
> method virtual head : 'a
> method virtual tail : 'a o_list
> end
> 
> Why the unit parameter? Why not just


Why not ? I must admit that I wont use it, but it's a matter of
style. 

> Also, why not just have a class type instead? Thus:
> 
> class type ['a] o_list = ...
> 
> Then the descendent classes can get rid of the inherit entirely.

the advantage of the inherit thing is that with this you are sure that
there is no typing problem, that you have do no misspelling in the
name of the method, and thanks to it, you don't have to use explicit
typing as you need without it.

These example doesn't show the problem, but if you remove the cons
method and the inherit things, you will have type error :

class ['a] o_nil () =
object(self)()
method empty () = true
method head = raise EmptyList
method tail = raise EmptyList
end ;;
Some type variables are unbound in this type:
class ['a] o_nil :
unit ->
object method empty : unit -> bool method head : 'b method tail : 'c end
The method head has type 'a where 'a is unbound

So the inheritance of the virtual class remove such problem (one can
also use explicit typing, but it easier with inheritance : you reduce
all explicit typing in the virtual class).
-- 
Rémi Vanicat
vanicat@l...
http://dept-info.labri.u-bordeaux.fr/~vanicat