Browse thread
Optional fields in modules
- Alain Frisch
[
Home
]
[ Index:
by date
|
by threads
]
[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
[ 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 |
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