From 1e21784ce1a4859fb793496891bb1cac9b66984d Mon Sep 17 00:00:00 2001 From: Francois Berenger <737920+UnixJunkie@users.noreply.github.com> Date: Tue, 9 Oct 2018 10:43:06 +0900 Subject: [PATCH] added List.counts, related to List.count (#230) - add `List.count_true_false` related to `List.count` --- AUTHORS.adoc | 1 + src/core/CCList.ml | 13 +++++++++++++ src/core/CCList.mli | 7 ++++++- src/core/CCListLabels.mli | 3 +++ 4 files changed, 23 insertions(+), 1 deletion(-) diff --git a/AUTHORS.adoc b/AUTHORS.adoc index 4982f2d0..52aa14d6 100644 --- a/AUTHORS.adoc +++ b/AUTHORS.adoc @@ -31,4 +31,5 @@ - Christopher Zimmermann (@madroach) - Jules Aguillon (@julow) - Metin Akat (@loxs) +- Francois Berenger (@UnixJunkie) - Hongchang Wu (@hongchangwu) diff --git a/src/core/CCList.ml b/src/core/CCList.ml index 8429faf1..b41ed2c3 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 count_true_false p l = + fold_left (fun (ok, ko) x -> + if p x then (ok + 1, ko) + else (ok, ko + 1) + ) (0, 0) l + +(*$T + count_true_false (fun x -> x mod 2 = 0) [] = (0, 0) + count_true_false (fun x -> x mod 2 = 0) [0; 0; 2; 4] = (4, 0) + count_true_false (fun x -> x mod 2 = 0) [1; 3; 5; 7] = (0, 4) + count_true_false (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..b8277b92 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 count_true_false : ('a -> bool) -> 'a list -> int * int +(** [let ok_count, ko_count = count_true_false p l in ...] + count_true_false 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..c3372361 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 count_true_false : 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.