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
Optional fields in modules
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: 2001-01-04 (20:19)
From: Alain Frisch <frisch@c...>
Subject: Optional fields in modules

I propose a tiny extension to the OCaml module system to allow optional
specification of *values* in signatures; for instance (I re-used the
keyword virtual):

sig virtual val f : int -> int end

A structure matches this signature if:
- it defines a value (or external primitive) f with the correct type,
- it doesn't define the value f

When accessing a field of a structure with this signature,
f has type (int -> int) option.

So, the coercion to this module type lifts the present identifiers
(convert them to "Some ...") and put "None" where absent identifiers are

This is very similar to optional arguments.

A typical use is to define "enriching functors": when some fields of the
argument are absent, replace them with default values.

Here is an example:
module type WRITER = sig  
  type t  
  val string : t -> string -> unit
  val char   : t -> char -> unit

module type WRITER_SKEL = sig
  type t
  virtual val string : t -> string -> unit
  virtual val char : t -> char -> unit

module FILL_IN (W : WRITER_SKEL) : WRITER with type t = W.t = struct
  type t = W.t

  let string, char = 
    match W.string, W.char with
    | Some string, Some char -> string, char
    | Some string, None -> 
        (fun w c -> string w (String.make 1 c))
    | None, Some char -> 
        (fun w s -> for i = 0 to String.length s - 1 do char w s.[i] done),
    | None, None -> failwith "Provide at least one of string, char !"

module Test = struct
  type t = unit
(* you can comment out one of : *)
  let string () s = Printf.printf "String [%s]\n" s
  let char () c = Printf.printf "Char [%c]\n" c

module Test' = FILL_IN (Test);;

The system is not powerful enough to express constraints such as
"string or char may be absent, but not both" (it is easy
to check this statically, but I don't see any light syntax to express the

I wrote a patch (against OCaml 3.00) implementing this proposal:


Supposing you are in a fresh source tree, you can apply it
with "patch -Np1 < patch-option", then build the system as usual.

Comments are welcome.

  Alain Frisch