Q7: nb_occurrences

Profil

nb_occurrences: typelt x liste -> entier

Exemples

nb_occurrences(a, (a b a a b c)) = 3
nb_occurrences(a, () ) = 0
nb_occurrences(a, (a b a a b c))
 =   1 + nb_occurrences(a, (b a a b c)) 
 =   1 + 0 + nb_occurrences(a, (a a b c)) 
 =   1 + 0 + 1 + nb_occurrences(a, (a b c)) 
 =   1 + 0 + 1 + 1 + nb_occurrences(a, (b c)) 
 =   1 + 0 + 1 + 1 + 0 + nb_occurrences(a, ( c )) 
 =   1 + 0 + 1 + 1 + 0 + 0 + nb_occurrences(a, ()) 
 =   1 + 0 + 1 + 1 + 0 + 0 + 0 
 =   3

Axiomes

nb_occurrences(a, liste_vide() ) = 0
nb_occurrences(a, cons(x, L)) = si_alors_sinon_finsi(a=x, 1, 0) + nb_occurrences(a, L)

Traduction en C

unsigned int nb_occurrences(TYPEELT val, liste L)
{
  if (est_vide(L))
  {
    return 0;
  }
  else
  {
    return ((val == prem(L))?1:0) + nb_occurrences(val, reste(L));
  }
}