Home page > OCaml > Private records in OCaml
Private records in OCaml
Tuesday 15 June 2010, by
In Private type abbreviations, what are they good for? [1] and then in Another use for private type abbreviations [2], yminsky wrote about the use of private type in OCaml.
Among the various proposed examples, the idea of read-only value was mentioned in the second post. I may have not followed the whole discussion after this, but I came on to an example in ocaml-ao today.
In ao, a driver is handled with an int, its id. It also has several read-only values, name, short_name etc..
Using a private record, it is possible to create a driver type this way:
(** Driver type (private). *)
type driver_t = private
{ id : int ;
kind : driver_kind_t ;
short_name : string ;
name : string ;
comment : string ;
author : string ;
priority : int ;
preferred_byte_format : byte_format_t ;
options : string list
}That way, one can access directly the fields of the record without being able to write a fresh one. In our case for instance, we then make sure that the id field, used when opening a device, is always a valid entry.
Another suggested use was, for bindings, when you have an extra internal field, like a state represented by a C void pointer. In this case, you may declare an object with n+1 element in the C function an only export the n first one as a private record type.. Its a bit hacky but it may be useful as well...

2 Forum messages