From 352b7e39019a07bf5171d9aa1570cfe61f6f4a09 Mon Sep 17 00:00:00 2001 From: Simon Cruanes Date: Wed, 17 Dec 2014 10:22:27 +0100 Subject: [PATCH] CCHashtbl.map_list --- src/core/CCHashtbl.ml | 20 +++++++++++++++++++- src/core/CCHashtbl.mli | 8 +++++++- 2 files changed, 26 insertions(+), 2 deletions(-) diff --git a/src/core/CCHashtbl.ml b/src/core/CCHashtbl.ml index 1a00239a..fe5289b7 100644 --- a/src/core/CCHashtbl.ml +++ b/src/core/CCHashtbl.ml @@ -40,6 +40,16 @@ let keys tbl k = Hashtbl.iter (fun key _ -> k key) tbl let values tbl k = Hashtbl.iter (fun _ v -> k v) tbl +let map_list f h = + Hashtbl.fold + (fun x y acc -> f x y :: acc) + h [] + +(*$T + of_list [1,"a"; 2,"b"] |> map_list (fun x y -> string_of_int x ^ y) \ + |> List.sort Pervasives.compare = ["1a"; "2b"] +*) + let to_seq tbl k = Hashtbl.iter (fun key v -> k (key,v)) tbl let of_seq seq = @@ -71,6 +81,9 @@ module type S = sig val values : 'a t -> 'a sequence (** Iterate on values in the table *) + val map_list : (key -> 'a -> 'b) -> 'a t -> 'b list + (** Map on a hashtable's items, collect into a list *) + val to_seq : 'a t -> (key * 'a) sequence (** Iterate on values in the table *) @@ -95,6 +108,11 @@ module Make(X : Hashtbl.HashedType) = struct let values tbl k = iter (fun _ v -> k v) tbl + let map_list f h = + fold + (fun x y acc -> f x y :: acc) + h [] + let to_seq tbl k = iter (fun key v -> k (key,v)) tbl let of_seq seq = @@ -215,7 +233,7 @@ module MakeCounter(X : Hashtbl.HashedType) = struct let n = get tbl x in T.replace tbl x (n+1) - let incr_by tbl n x = + let incr_by tbl n x = let n' = get tbl x in if n' + n <= 0 then T.remove tbl x diff --git a/src/core/CCHashtbl.mli b/src/core/CCHashtbl.mli index 5eb6acf1..abee28de 100644 --- a/src/core/CCHashtbl.mli +++ b/src/core/CCHashtbl.mli @@ -25,7 +25,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *) -(** {1 Extension to the standard Hashtbl} +(** {1 Extension to the standard Hashtbl} @since 0.4 *) @@ -44,6 +44,9 @@ val keys : ('a,'b) Hashtbl.t -> 'a sequence val values : ('a,'b) Hashtbl.t -> 'b sequence (** Iterate on values in the table *) +val map_list : ('a -> 'b -> 'c) -> ('a, 'b) Hashtbl.t -> 'c list +(** Map on a hashtable's items, collect into a list *) + val to_seq : ('a,'b) Hashtbl.t -> ('a * 'b) sequence (** Iterate on bindings in the table *) @@ -70,6 +73,9 @@ module type S = sig val values : 'a t -> 'a sequence (** Iterate on values in the table *) + val map_list : (key -> 'a -> 'b) -> 'a t -> 'b list + (** Map on a hashtable's items, collect into a list *) + val to_seq : 'a t -> (key * 'a) sequence (** Iterate on values in the table *)