From 78ee7e5c2f32761a10f953dbf0233c9f34d98df1 Mon Sep 17 00:00:00 2001 From: Jacques-Pascal Deplaix Date: Sun, 3 Dec 2017 21:30:26 +0000 Subject: [PATCH] Add List.count --- src/core/CCList.ml | 10 ++++++++++ src/core/CCList.mli | 4 ++++ 2 files changed, 14 insertions(+) diff --git a/src/core/CCList.ml b/src/core/CCList.ml index f7552587..290dbaa5 100644 --- a/src/core/CCList.ml +++ b/src/core/CCList.ml @@ -362,6 +362,16 @@ let flatten l = fold_right append l [] flatten (init 300_001 (fun x->[x])) = 0--300_000 *) +let count f l = + fold_left (fun n x -> if f x then succ n else n) 0 l + +(*$T + count (fun x -> x mod 2 = 0) [] = 0 + count (fun x -> x mod 2 = 0) [0; 0; 2; 4] = 4 + count (fun x -> x mod 2 = 0) [1; 3; 5; 7] = 0 + count (fun x -> x mod 2 = 0) [2; 6; 9; 4] = 3 +*) + 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 f83407bf..cb5a379b 100644 --- a/src/core/CCList.mli +++ b/src/core/CCList.mli @@ -76,6 +76,10 @@ val fold_flat_map : ('acc -> 'a -> 'acc * 'b list) -> 'acc -> 'a list -> 'acc * list to a list of lists that is then [flatten]'d.. @since 0.14 *) +val count : ('a -> bool) -> 'a list -> int +(** [count f l] counts how much element of [l] comply with the function [f]. + @since NEXT_RELEASE *) + val init : int -> (int -> 'a) -> 'a t (** Similar to {!Array.init} @since 0.6 *)