use a functor rather than first-class modules, for Set

This commit is contained in:
Simon Cruanes 2013-01-29 14:11:47 +01:00
parent ee4ce9c9ba
commit 1e90120295
3 changed files with 25 additions and 13 deletions

View file

@ -128,6 +128,8 @@ module List =
struct
let of_seq seq = List.rev (fold (fun y x -> x::y) [] seq)
let of_rev_seq seq = fold (fun y x -> x :: y) [] seq
let to_seq l = from_iter (fun k -> List.iter k l)
end
@ -191,15 +193,16 @@ module Int =
{ seq_fun; }
end
module Set =
(** Iterate on sets. The functor must be instantiated with a set type *)
module Set(S : Set.S) =
struct
let to_seq (type s) (type t) m set =
let module S = (val m : Set.S with type elt = s and type t = t) in
from_iter (fun k -> S.iter k set)
type set = S.t
let of_seq (type s) (type t) m seq =
let module S = (val m : Set.S with type elt = s and type t = t) in
fold (fun set x -> S.add x set) S.empty seq
type elt = S.elt
let to_seq set = from_iter (fun k -> S.iter k set)
let of_seq seq = fold (fun set x -> S.add x set) S.empty seq
end
(** {2 Pretty printing of sequences} *)

View file

@ -85,6 +85,9 @@ module List :
sig
val of_seq : 'a t -> 'a list
val of_rev_seq : 'a t -> 'a list
(** Get the list of the reversed sequence (more efficient) *)
val to_seq : 'a list -> 'a t
end
@ -146,11 +149,16 @@ module Int :
sequences. *)
end
(** Iterate on sets. The Set module has to be provided. *)
module Set :
(** Iterate on sets. The functor must be instantiated with a set type *)
module Set(S : Set.S) :
sig
val to_seq : (module Set.S with type elt = 'a and type t = 'b) -> 'b -> 'a t
val of_seq : (module Set.S with type elt = 'a and type t = 'b) -> 'a t -> 'b
type set = S.t
type elt = S.elt
val to_seq : set -> elt t
val of_seq : elt t -> set
end
(** {2 Pretty printing of sequences} *)

View file

@ -7,6 +7,7 @@ let pp_list ?(sep=", ") pp_item formatter l =
(** Set of integers *)
module ISet = Set.Make(struct type t = int let compare = compare end)
module ISetSeq = Sequence.Set(ISet)
let _ =
let l = [0;1;2;3;4;5;6] in
@ -24,12 +25,12 @@ let _ =
in
let l3 = Sequence.List.of_seq (Sequence.rev (Sequence.Int.range ~start:0 ~stop:42)) in
let set = List.fold_left (fun set x -> ISet.add x set) ISet.empty [4;3;100;42] in
let s = (module ISet : Set.S with type elt = int and type t = ISet.t) in
let l4 = Sequence.List.of_seq (Sequence.Set.to_seq s set) in
let l4 = Sequence.List.of_seq (ISetSeq.to_seq set) in
Format.printf "l=@[<h>[%a]@]@." (pp_list Format.pp_print_int) l;
Format.printf "l'=@[<h>[%a]@]@." (pp_list Format.pp_print_int) l';
Format.printf "l''=@[<h>[%a]@]@." (pp_list Format.pp_print_int) l'';
Format.printf "l2=@[<h>[%a]@]@." (pp_list Format.pp_print_string) l2;
Format.printf "l3=@[<h>[%a]@]@." (pp_list Format.pp_print_int) l3;
Format.printf "s={@[<h>%a@]}@." (Sequence.pp_seq Format.pp_print_int) (ISetSeq.to_seq set);
Format.printf "l4=@[<h>[%a]@]@." (pp_list Format.pp_print_int) l4;
()