Home page > OCaml > Private records in OCaml

Private records in OCaml

Tuesday 15 June 2010, by Toots

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

  • Private records in OCaml Le 15 June 2010 à 08:54 , by Julien

    What you use is a private type, not a private type abbreviation as discussed by Yaron Minsky.

    While there are several well known context where private types are very useful (like the one you described indeed), there are not so much examples where private type abbreviations are useful.

    Reply to this message

  • Private records in OCaml Le 23 June 2010 à 02:19 , by Toots

    I guess you should precise what is a private type abbreviation. In the module’s code, the type is not private. It is declared private in the signature of the module’s mli. So far, its seems very similar to the introductory presentation of private abbreviation in the first link...

    Reply to this message

Reply to this article