diff --git a/sequence.ml b/sequence.ml index f658f88..f3142d8 100644 --- a/sequence.ml +++ b/sequence.ml @@ -187,6 +187,12 @@ module Hashtbl = let to_seq h = from_iter (fun k -> Hashtbl.iter (fun a b -> k (a, b)) h) + + let keys h = + from_iter (fun k -> Hashtbl.iter (fun a b -> k a) h) + + let values h = + from_iter (fun k -> Hashtbl.iter (fun a b -> k b) h) end module String = @@ -222,6 +228,25 @@ module Set(S : Set.S) = let of_seq seq = fold (fun set x -> S.add x set) S.empty seq end +(** Iterate on maps. The functor must be instantiated with a map type *) +module Map(M : Map.S) = + struct + type 'a map = 'a M.t + type key = M.key + + let to_seq m = + from_iter (fun k -> M.iter (fun key value -> k (key, value)) m) + + let keys m = + from_iter (fun k -> M.iter (fun key _ -> k key) m) + + let values m = + from_iter (fun k -> M.iter (fun _ value -> k value) m) + + let of_seq seq = + fold (fun m (key,value) -> M.add key value m) M.empty seq + end + (** {2 Pretty printing of sequences} *) (** Pretty print a sequence of ['a], using the given pretty printer diff --git a/sequence.mli b/sequence.mli index 4eb2cb4..25791ef 100644 --- a/sequence.mli +++ b/sequence.mli @@ -135,6 +135,9 @@ module Hashtbl : val to_seq : ('a, 'b) Hashtbl.t -> ('a * 'b) t (** Sequence of key/value pairs from the hashtable *) + + val keys : ('a, 'b) Hashtbl.t -> 'a t + val values : ('a, 'b) Hashtbl.t -> 'b t end module String : @@ -166,6 +169,21 @@ module Set(S : Set.S) : val of_seq : elt t -> set end +(** Iterate on maps. The functor must be instantiated with a map type *) +module Map(M : Map.S) : + sig + type 'a map = 'a M.t + type key = M.key + + val to_seq : 'a map -> (key * 'a) t + + val keys : 'a map -> key t + + val values : 'a map -> 'a t + + val of_seq : (key * 'a) t -> 'a map + end + (** {2 Pretty printing of sequences} *) val pp_seq : ?sep:string -> (Format.formatter -> 'a -> unit) ->