make count lazy

This commit is contained in:
Simon Cruanes 2017-12-15 12:46:59 +01:00
parent 6be7dddee2
commit c3590de261
2 changed files with 10 additions and 7 deletions

View file

@ -446,14 +446,16 @@ let count (type k) ?(hash=Hashtbl.hash) ?(eq=(=)) seq =
let hash = hash let hash = hash
end) in end) in
(* compute group table *) (* compute group table *)
let tbl = lazy (
let tbl = Tbl.create 32 in let tbl = Tbl.create 32 in
seq seq
(fun x -> (fun x ->
let n = try Tbl.find tbl x with Not_found -> 0 in let n = try Tbl.find tbl x with Not_found -> 0 in
Tbl.replace tbl x (n+1) Tbl.replace tbl x (n+1));
); tbl
) in
fun yield -> fun yield ->
Tbl.iter (fun x n -> yield (x,n)) tbl Tbl.iter (fun x n -> yield (x,n)) (Lazy.force tbl)
(*$R (*$R
[1;2;3;3;2;2;3;4] [1;2;3;3;2;2;3;4]

View file

@ -276,6 +276,7 @@ val count : ?hash:('a -> int) -> ?eq:('a -> 'a -> bool) ->
'a t -> ('a * int) t 'a t -> ('a * int) t
(** Map each distinct element to its number of occurrences in the whole seq. (** Map each distinct element to its number of occurrences in the whole seq.
Similar to [group_by seq |> map (fun l->List.hd l, List.length l)] Similar to [group_by seq |> map (fun l->List.hd l, List.length l)]
precondition: for any [x] and [y], if [eq x y] then [hash x=hash y] must hold.
@since 0.10 *) @since 0.10 *)
val uniq : ?eq:('a -> 'a -> bool) -> 'a t -> 'a t val uniq : ?eq:('a -> 'a -> bool) -> 'a t -> 'a t