From d304bca14a1cf796600eec129a041bdeba68e393 Mon Sep 17 00:00:00 2001 From: Francois BERENGER Date: Fri, 5 Oct 2018 14:29:29 +0900 Subject: [PATCH] added List.counts, related to List.count --- src/core/CCList.ml | 13 +++++++++++++ src/core/CCList.mli | 7 ++++++- src/core/CCListLabels.mli | 3 +++ 3 files changed, 22 insertions(+), 1 deletion(-) diff --git a/src/core/CCList.ml b/src/core/CCList.ml index 8429faf1..a46f77be 100644 --- a/src/core/CCList.ml +++ b/src/core/CCList.ml @@ -382,6 +382,19 @@ let count f l = count (fun x -> x mod 2 = 0) [2; 6; 9; 4] = 3 *) +let counts p l = + fold_left (fun (ok, ko) x -> + if p x then (ok + 1, ko) + else (ok, ko + 1) + ) (0, 0) l + +(*$T + counts (fun x -> x mod 2 = 0) [] = (0, 0) + counts (fun x -> x mod 2 = 0) [0; 0; 2; 4] = (4, 0) + counts (fun x -> x mod 2 = 0) [1; 3; 5; 7] = (0, 4) + counts (fun x -> x mod 2 = 0) [2; 6; 9; 4] = (3, 1) +*) + let product f l1 l2 = flat_map (fun x -> map (fun y -> f x y) l2) l1 diff --git a/src/core/CCList.mli b/src/core/CCList.mli index 53aaa34a..2254a202 100644 --- a/src/core/CCList.mli +++ b/src/core/CCList.mli @@ -86,9 +86,14 @@ val fold_flat_map : ('acc -> 'a -> 'acc * 'b list) -> 'acc -> 'a list -> 'acc * @since 0.14 *) val count : ('a -> bool) -> 'a list -> int -(** [count f l] counts how much elements of [l] comply with the function [f]. +(** [count p l] counts how many elements of [l] satisfy predicate [p]. @since 1.5 *) +val counts : ('a -> bool) -> 'a list -> int * int +(** [let ok_count, ko_count = counts p l in ...] + counts how many elements of [l] satisfy (resp. violate) predicate [p]. + @since NEXT_RELEASE *) + val init : int -> (int -> 'a) -> 'a t (** [init len f] is [f 0; f 1; ...; f (len-1)]. @raise Invalid_argument if len < 0. diff --git a/src/core/CCListLabels.mli b/src/core/CCListLabels.mli index ff9deb91..1b8c8e38 100644 --- a/src/core/CCListLabels.mli +++ b/src/core/CCListLabels.mli @@ -86,6 +86,9 @@ val fold_flat_map : f:('acc -> 'a -> 'acc * 'b list) -> init:'acc -> 'a list -> val count : f:('a -> bool) -> 'a list -> int (** @since 2.2 *) +val counts : f:('a -> bool) -> 'a list -> int * int +(** @since NEXT_RELEASE *) + val init : int -> f:(int -> 'a) -> 'a t (** [init len ~f] is [f 0; f 1; ...; f (len-1)]. @raise Invalid_argument if len < 0.