01.06.2013 Views

Appel initial : Le premier appel de la fonction.

Appel initial : Le premier appel de la fonction.

Appel initial : Le premier appel de la fonction.

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Exercices complémentaires :<br />

a. Création d'une liste d'entiers qui contient les n <strong>premier</strong>s entiers > 0<br />

Récursivité c<strong>la</strong>ssique :<br />

let rec create_first_n_strictly_positive_integers_list n =<br />

match n=0 with<br />

|true -> []<br />

|_ -> n::create_first_n_strictly_positive_integers_list (n-1);;<br />

val create_first_n_strictly_positive_integers : int -> int list = <br />

create_first_n_strictly_positive_integers_list 6;;<br />

- : int list = [6; 5; 4; 3; 2; 1]<br />

<strong>Le</strong>s entiers sont ordonnées par ordre décroissant. Si on désire les ordonner par ordre<br />

croissant on utilisera l'opérateur <strong>de</strong> concaténation au lieu <strong>de</strong> l'opérateur d'insertion pour<br />

construire <strong>la</strong> liste.<br />

let rec create_first_n_strictly_positive_integers_list n =<br />

match n=0 with<br />

|true -> []<br />

|_ -> create_first_n_strictly_positive_integers_list (n-1)@[n];;<br />

val create_first_n_strictly_positive_integers : int -> int list = <br />

create_first_n_strictly_positive_integers_list 6;;<br />

- : int list = [1; 2; 3; 4; 5; 6]<br />

Récursivité terminale :<br />

let create_first_n_strictly_positive_integers_list n =<br />

let rec auxiliaire accumu<strong>la</strong>teur n =<br />

match n=0 with<br />

|true -> accumu<strong>la</strong>teur<br />

|_ -> auxiliaire (n::accumu<strong>la</strong>teur) (n-1)<br />

in<br />

auxiliaire [] n;;<br />

val create_first_n_strictly_positive_integers_list : int -> int list = <br />

create_first_n_strictly_positive_integers_list 6;;<br />

- : int list = [1; 2; 3; 4; 5; 6]

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!