added List.counts, related to List.count

This commit is contained in:
Francois BERENGER 2018-10-05 14:29:29 +09:00
parent 3b1de9a1c8
commit d304bca14a
3 changed files with 22 additions and 1 deletions

View file

@ -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

View file

@ -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.

View file

@ -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.