English version
Accueil     À propos     Téléchargement     Ressources     Contactez-nous    

Ce site est rarement mis à jour. Pour les informations les plus récentes, rendez-vous sur le nouveau site OCaml à l'adresse ocaml.org.

Browse thread
Classes AND Modules? What's the point?
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: 1999-11-04 (18:50)
From: William Chesters <williamc@d...>
Subject: Classes AND Modules? What's the point?
Mark Engelberg writes:
 > The thing that confuses me the most about OCaml is that there is a huge
 > overlap between the functionality of classes and modules, with a couple of
 > subtle differences.

   Interestingly, the big difference is that modules are not "first
class values".  You can't pass the whole thing around, along with its
dispatch table, like you can an object.  You can't write

	module type Shape = sig
	  val area: unit -> float

	module Square (Init: sig val side: float end) = struct
	  let side = Init.side
	  let area () = side *. side

	let foo M = M.area ()     (* this isn't allowed *)

	let _ =
	  let module It = Square (struct let side = 50. end)
	  foo It                  (* nor is this *)

So although you can create modules on the fly with "let module", and
pass their _members_ around, you can't really use the instantiations
conveniently as objects.  There is no way to use modules per se to
achieve class-style polymorphism.

   I have often thought that you could get something very like the
ocaml class system, with similar semantics and implementational
issues, by this kind of route.

 > The problem is that because modules are slightly more powerful, it appears
 > that the entire standard library is implemented as modules, not classes,
 > despite the fact that this is supposed to be Object-oriented Caml!

   IIRC OLabl ships with object versions of some of the libraries.

   Don't forget that object a method invocation is a little slower
than a module function call---I measured fetches from a Hashtbl,
indirected through an object wrapper, about 10% slower than fetches
indirected through a module.  Anyway, object-using programs don't
always necessarily work out prettier than module-based ones.