Browse thread
Re: Create a constraint between variant type and data list
- oleg@o...
[
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: | -- (:) |
| From: | oleg@o... |
| Subject: | Re: Create a constraint between variant type and data list |
Sylvain Le Gall wrote:
> I would like to define:
>
> type license = GPL | LGPL
>
> and
>
> let data = [ GPL, "GNU Public license";
> LGPL, "GNU Lesser General Public license" ]
>
> I would like to enforce that all variants of license are in the
> association list.
In other words, you would like a set of values of a distinct type,
each of which is associated with a printable string. One should be
able to add to the set in some `authorized way'; one should not be
able to make a value of that distinct type in an unauthorized way
(that is, by accident). Right?
It seems the following solution then would satisfy the specification:
module LICENSE : sig
type t
val print_lic : t -> string
val gpl : t
val lgpl : t
(* more can be added *)
end = struct
type t = string
let print_lic x = x
let gpl = "GNU Public license"
let lgpl = "GNU Lesser General Public license"
end;;
(* Usage example *)
type package = {pkg_name : string; pkg_lic : LICENSE.t};;
let packages = [{pkg_name = "gcc"; pkg_lic = LICENSE.gpl};
{pkg_name = "lgpled"; pkg_lic = LICENSE.lgpl}]
;;
let rec pr_lics = function [] -> ()
| {pkg_lic = l}::t -> Printf.printf "%s\n" (LICENSE.print_lic l);
pr_lics t
;;
let rec all_of_lic l = function [] -> []
| {pkg_name = name; pkg_lic = l'}::t when l' == l -> name :: all_of_lic l t
| _::t -> all_of_lic l t
;;
all_of_lic LICENSE.lgpl packages;;
One can't overlook specifying the description string. One can't create
new values of the type LICENSE.t `by accident' (the only possible
values of the type are the ones exported by the module).