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
OCaml object types vs record types
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: 2007-06-04 (16:45)
From: Raj B <rajb@r...>
Subject: OCaml object types vs record types
Hi there

I'm writing an application where I'd modeling objects as record  
types. However, I'd like to have a subtyping relation between them  
along with (occasional) coercion. For example,

type obj = {name : string}
type specialobj = {name: string; mutable value: int;...}
and so on...

Obviously, records obviously don't allow me to do this. In fact, I  
can't even define two record types with the same field 'name'. I have  
to define the 'largest' possible type i.e. specialobj and just leave  
fields undefined (default value) when I don't need them. This is  
fine, except that it eats up tons of memory because my records are  
quite large and slows things down. On profiling, I find that most of  
my time goes in the OCaml function 'caml_dup', which, I believe,  
copies structures. I am very concerned about speed in my application.

I'm not sure I need the entire machinery of classes (since, I  
understand that it can be pretty slow too?) and all that goes with  
it, so I was wondering if using object types might serve the purpose.

type obj = <name : string>
type specialobj = <name: string; mutable value: int;...>

Unfortunately, it doesn't seem possible to define 'mutable' fields in  
the same way as records. I'd have to define methods to get and set  
values, so it seems like there's very little difference from class  
definitions. Please correct me if I'm wrong.

Is there any way to get what I want (records with subtyping/coercion  
behavior) without using classes? In case I do end up using classes,  
what kind of performance penalty am I looking at?