Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!

Idiom #316 Count occurrences in a list

Determine the number c of elements in the list x that satisfy the predicate p.

import java.util.ArrayList;
import java.util.Collections;
int c = Collections.frequency(x, p);
  
c=count(p(x))
c := 0
for _, v := range x {
	if p(v) {
		c++
	}
}
func count[T any](x []T, p func(T) bool) int {
	c := 0
	for _, v := range x {
		if p(v) {
			c++
		}
	}
	return c
}
let c = x.filter(p).length
  c := 0;
  for el in x do if p(el) then Inc(c);
my $c = grep { p($_) } @x;
c = sum(p(v) for v in x)
c = x.count{|el| p(el) }

New implementation...