Merge pull request #162 from jpdeplaix/list_count

Add `List.count`
This commit is contained in:
Simon Cruanes 2017-12-03 22:37:27 +01:00 committed by GitHub
commit 16a7ff6d4e
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 14 additions and 0 deletions

View file

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

View file

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