Version française
Home     About     Download     Resources     Contact us    
Browse thread
Create a constraint between variant type and data list
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Anil Madhavapeddy <anil@r...>
Subject: Re: [Caml-list] Create a constraint between variant type and data list
Here's a (very) quick and dirty implementation that will automatically populate data, using our dynamic typing library ( http://github.com/mirage/dyntype ).  You just need to fill in desc_of_license with the matching descriptions, and data will be auto-populated at program startup.

-anil

--
type license = GPL | LGPL with type_of,value

(* For a type, generate a description string *)
let desc_of_license = function
  |"GPL",_ -> "GNU General Public License"
  |"LGPL",_ -> "GNU Lesser GPL"
  |_ -> failwith "unknown license"

(* Generate a list of license types *)
let licenses = match type_of_license with 
  | Type.Ext ("license", Type.Sum ts) -> ts 
  | _ -> assert false

(* From a license type, generate a Value of that type *)
let value_of_license_t = function
  |name,[] -> Value.Ext (("",0L), Value.Sum (name,[]))
  |name,_ -> failwith "no args allowed"

(* Populate data with licenses and their description *)
let data = List.map 
  (fun lic ->
    (license_of_value (value_of_license_t lic)) , 
    (desc_of_license lic)
  ) licenses

let _ =
  Printf.printf "GPL: %s\n%!" (List.assoc GPL data);
  Printf.printf "LGPL: %s\n%!" (List.assoc LGPL data)
--

-anil

On 3 Sep 2010, at 18:16, Sylvain Le Gall wrote:

> Hello all,
> 
> I would like to somehow enforce that a variant type is associated with
> an entry in a data list. 
> 
> For example, 
> 
> 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.
> 
> I have tried to use polymorphic variants, but don't see how to enforce
> this constraint.
> 
> The point, is that if I add a new variant to license (e.g. BSD3), the
> compiler output an error because this new variant is not in data list.
> 
> Any ideas ? If you need to use another type expression rather than
> variant, please do so, as long as I am able to link the license type
> and data list.
> 
> Thanks all,
> Sylvain Le Gall
> 
> _______________________________________________
> Caml-list mailing list. Subscription management:
> http://yquem.inria.fr/cgi-bin/mailman/listinfo/caml-list
> Archives: http://caml.inria.fr
> Beginner's list: http://groups.yahoo.com/group/ocaml_beginners
> Bug reports: http://caml.inria.fr/bin/caml-bugs