From 01e008256c4de5a6144ed821f95879d180040558 Mon Sep 17 00:00:00 2001 From: Simon Cruanes Date: Mon, 4 Mar 2013 17:30:34 +0100 Subject: [PATCH] hashset.union/inter take an optional argument for the resulting set --- hashset.ml | 19 +++++++++++++------ hashset.mli | 8 +++++--- 2 files changed, 18 insertions(+), 9 deletions(-) diff --git a/hashset.ml b/hashset.ml index bdbc058d..e7dd8b8d 100644 --- a/hashset.ml +++ b/hashset.ml @@ -55,10 +55,17 @@ let to_seq set = let of_seq set seq = Sequence.iter (fun x -> add set x) seq -let union s1 s2 = - of_seq s1 (to_seq s2) +let union ?into (s1 : 'a t) (s2 : 'a t) = + let into = match into with + | Some s -> of_seq s (to_seq s1); s + | None -> copy s1 in + of_seq into (to_seq s2); + into -let inter s1 s2 = - let set = copy s1 in - filter (fun x -> mem s2 x) set; - set +let inter ?into (s1 : 'a t) (s2 : 'a t) = + let into = match into with + | Some s -> s + | None -> empty ~eq:s1.PHashtbl.eq ~hash:s1.PHashtbl.hash (cardinal s1) in + (* add to [into] elements of [s1] that also belong to [s2] *) + of_seq into (Sequence.filter (fun x -> mem s2 x) (to_seq s1)); + into diff --git a/hashset.mli b/hashset.mli index c56c5ce5..f6821655 100644 --- a/hashset.mli +++ b/hashset.mli @@ -34,7 +34,7 @@ val empty : ?max_load:float -> ?eq:('a -> 'a -> bool) -> val copy : 'a t -> 'a t -val clear : 'a t -> 'a t +val clear : 'a t -> unit val cardinal : 'a t -> int @@ -55,6 +55,8 @@ val to_seq : 'a t -> 'a Sequence.t val of_seq : 'a t -> 'a Sequence.t -> unit -val union : 'a t -> 'a t -> 'a t +val union : ?into:'a t -> 'a t -> 'a t -> 'a t + (** Set union. The result is stored in [into] *) -val inter : 'a t -> 'a t -> 'a t +val inter : ?into:'a t -> 'a t -> 'a t -> 'a t + (** Set intersection. The result is stored in [into] *)