caml-list - the Caml user's mailing list
 help / color / mirror / Atom feed
* Optional fields in modules
@ 2001-01-04 18:05 Alain Frisch
  0 siblings, 0 replies; only message in thread
From: Alain Frisch @ 2001-01-04 18:05 UTC (permalink / raw)
  To: Caml list

Hello,

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,
or
- 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
expected.

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
end;;

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

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 -> 
        string, 
        (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),
        char
    | None, None -> failwith "Provide at least one of string, char !"
end;;

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
end;;

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
constraint).

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

http://www.eleves.ens.fr:8080/home/frisch/info/patch-option

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



^ permalink raw reply	[flat|nested] only message in thread

only message in thread, other threads:[~2001-01-04 20:19 UTC | newest]

Thread overview: (only message) (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2001-01-04 18:05 Optional fields in modules Alain Frisch

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for NNTP newsgroup(s).