hashset.union/inter take an optional argument for the resulting set

This commit is contained in:
Simon Cruanes 2013-03-04 17:30:34 +01:00
parent d52441018c
commit 01e008256c
2 changed files with 18 additions and 9 deletions

View file

@ -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

View file

@ -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] *)