English version
Accueil     À propos     Téléchargement     Ressources     Contactez-nous    

Ce site est rarement mis à jour. Pour les informations les plus récentes, rendez-vous sur le nouveau site OCaml à l'adresse ocaml.org.

Browse thread
Instanciating functor types with extra parameters
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: 2007-08-04 (16:15)
From: Denis Bueno <dbueno@g...>
Subject: Re: [Caml-list] Instanciating functor types with extra parameters
On 8/4/07, Arnaud Spiwack <aspiwack@lix.polytechnique.fr> wrote:
> When I have a functor type, like for example (not too innocent I'm afraid) :
> module type OrderedType =
>   sig
>     type t
>     val compare : t -> t -> int
>   end
> Something that naive intuition would allow you to do is something like :
> module GenOrder : OrderedType =
>   struct
>     type t = 'a
>     let compare = compare
>   end
[... snip ...]
> My point is that I know absolutely no way of doing such a thing. Hence I
> can't make a set with total or partial genericity. If I want to add type
> parameters I have to rewrite the *whole* set library. Actually... I've
> got to copy past it, and replace all occurences of    t   with an 'a t
> for instance. Or ('a,'b) t if I have two arguments. I really had to do
> that once, and almost a couple of other time. That's why it infuriates
> me as I said earlier.

You can do something slightly less general that certainly doesn't
require rewriting the whole set library:  One comparator definition
per set you'd like to create.

module StringOrder : OrderedType = struct
  type t = string
  (* just to be clear about which compare to capture)
  let compare = Pervasives.compare

module IntOrder : OrderedType = struct
  type t = int
  let compare = Pervasives.compare

... and so on.  You can use these to create functors, of course:

module StringSet = Set.Make (StringOrder)
module IntSet = Set.Make (IntSet)

I think you'll find, though, as time goes on that you'll use special
comparators: that is, not just generic string comparison, but some
other total order on strings.  And you'll want to name
MySpecialStringCompare accordnigly.

module CaseInsensitiveStrOrder : OrderedType = struct
  type t = string
  let compare x y = Pervasives.compare (downcase x) (downcase y)
module CaseInsensitiveSet = Set.Make (CaseInsensitiveStrOrder)

"Program testing can be used to show the presence of bugs, but never to show
their absence." -- Edsger Dijkstra