more functions on Hashtbl;

functor for conversion between Map and Sequence
This commit is contained in:
Simon Cruanes 2013-01-29 14:40:11 +01:00
parent 087c38aa0c
commit 0b47a10e9b
2 changed files with 43 additions and 0 deletions

View file

@ -187,6 +187,12 @@ module Hashtbl =
let to_seq h = let to_seq h =
from_iter (fun k -> Hashtbl.iter (fun a b -> k (a, b)) 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 end
module String = 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 let of_seq seq = fold (fun set x -> S.add x set) S.empty seq
end 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} *) (** {2 Pretty printing of sequences} *)
(** Pretty print a sequence of ['a], using the given pretty printer (** Pretty print a sequence of ['a], using the given pretty printer

View file

@ -135,6 +135,9 @@ module Hashtbl :
val to_seq : ('a, 'b) Hashtbl.t -> ('a * 'b) t val to_seq : ('a, 'b) Hashtbl.t -> ('a * 'b) t
(** Sequence of key/value pairs from the hashtable *) (** 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 end
module String : module String :
@ -166,6 +169,21 @@ module Set(S : Set.S) :
val of_seq : elt t -> set val of_seq : elt t -> set
end 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} *) (** {2 Pretty printing of sequences} *)
val pp_seq : ?sep:string -> (Format.formatter -> 'a -> unit) -> val pp_seq : ?sep:string -> (Format.formatter -> 'a -> unit) ->