Q5: inserer_element

Profil

inserer_element: typelt x entier x liste -> liste

Exemple

inserer_element(x, 1, L) = cons(x, L)

inserer_element(x, 1, (a b c) ) = (x a b c)

inserer_element(x, 2, (a b c)) = (a x b c)
 =  cons(a, inserer_element(x, 1, (b c))

Axiomes

inserer_element(x, n, l_vide()) = si_alors_sinon_finsi(n = 1, cons(x, l_vide()), Erreur)

inserer_element(x, n, cons(y, L)) = si_alors_sinon_finsi(n = 1, cons(x, cons(y, L)), cons(y, inserer_element(x, n-1, L)))

Traduction en C

liste inserer_element(TYPEELT val, unsigned int n, liste L)
{
  if (est_vide(L))
  {
    if (n != 1)
    {
       printf("Erreur d'insertion dans inserer_element: liste_vide et n != 0\n");
       exit(EXIT_FAILURE);
    }
    else
    {
      return cons(val, liste_vide());
    }
  }
  else
  {
    if (n == 1)
    {
      return cons(val, L);
    }
    else
    {
      return cons(prem(L), inserer_element(val, n-1, reste(L)));
    }
  }
}