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: Ashish Agarwal <agarwal1975@g...>
Subject: Re: [Caml-list] Create a constraint between variant type and data list
See the Enum section of deriving:
http://code.google.com/p/deriving/wiki/Introduction

I haven't used it myself so cannot comment on how well it works.


On Fri, Sep 3, 2010 at 2:51 PM, Martin Jambon <martin.jambon@ens-lyon.org>wrote:

> 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.
>
> I don't see a solution other than meta-programming or runtime checks.
>
> Here is a simple code generator that would do the job:
>
> (* license_gen.ml *)
> open Printf
>
> let print_licenses l =
>  printf "type license =";
>  List.iter (fun (k, v) -> printf " | %s" k) l;
>  printf "\n";
>  printf "let licences = [\n";
>  List.iter (fun (k, v) -> printf "  %s, %S;\n" k v) l;
>  printf "]\n"
>
> let () =
>  print_licenses [
>    "GPL", "GNU Public license";
>    "LGPL", "GNU Lesser General Public license";
>  ]
>
> (* end *)
>
> $ ocaml license_gen.ml > license.ml
>
>
>
> Martin
>
> --
> http://mjambon.com/
>
> _______________________________________________
> 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
>