Browse thread
'a Set?
[
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: | Jon Harrop <jon@j...> |
| Subject: | Re: [Caml-list] 'a Set? |
On Tuesday 25 January 2005 23:54, Mike Hamburg wrote:
> Is there a clean way to do this without removing the code from set.ml
> and modifying it?
I do not believe so. I have also had to do this.
Compared to a flat set of functions, the functor approach has the advantage of
enforcing a consistently used compare function. The same effect can be
achieved with "elt = 'a" by writing a higher-order function which returns a
record containing the Set.* functions using the given function argument as
the compare function. Something equivalent to this:
type 'a t = 'a list
type 'a set =
{ empty : 'a t;
is_empty : 'a t -> bool;
add : 'a -> 'a t -> 'a t;
mem : 'a -> 'a t -> bool }
let rec add compare e = function
[] -> [e]
| h :: t -> match compare h e with
-1 -> e :: h :: t
| 0 -> e :: t
| _ -> h :: add compare e t
let rec mem compare e = function
[] -> false
| h :: t -> match compare h e with
-1 -> false
| 0 -> true
| _ -> mem compare e t
let make ?(compare=compare) () =
{ empty = [];
is_empty = (fun s -> s=[]);
add = add compare;
mem = mem compare }
Possible issues with this are that building closures (i.e. in "make") is
expensive and that the resulting type is monomorphic ('_a). You can probably
get a polymorphic type most easily by putting the definitions of "add" etc.
in the record definition, rather than partially applying their arguments.
Cheers,
Jon.