On se propose de réécrire ici les fonctions intégrées de OCaml sur les listes.
On leur donnera le nom « my_func » si « func » est le nom de la fonction Caml à réécrire.
On écrira systématiquement des filtrages par cas.
Exercice 1. Réécrire les fonctions « List.hd : ‘a list -> a » et « List.tl : ‘a list -> ‘a list » |
Exercice 2. Réécrire la fonction « List.length : ‘a list -> int » |
Exercice 3. Réécrire la concaténation « (@) : ‘a list -> ‘a list -> ‘a list » (la nommer « my_concat »). |
Exercice 4. Réécrire la fonction « List.rev : ‘a list -> ‘a list » d’inversion d’une liste. |
Exercice 5. Réécrire « List.map : (‘a -> ‘b) -> ‘a list -> ‘a list » qui mappe une fonction sur une liste. |
Exercice 6. Réécrire « List.iter : (‘a -> ‘b) -> ‘a list -> unit » qui mappe une procédure sur une liste. |
Exercice 7. Réécrire la fonction d’itération « List.fold_left : (‘a -> ‘b -> ‘a) -> ‘a -> ‘b list -> ‘a » Rappel : « List.fold_left f a {b_{1};\ldots;b_{n}]} » renvoie « {f(\ldots(f(f a b_1) b_2)\ldots) b_{n})} » |
Exercice 8. Réécrire la fonction d’itération « List.fold_right : (‘a -> ‘b -> ‘b) -> ‘a list -> ‘b -> ‘b » Rappel : « List.fold_right {f\ [a_{1};\ldots;a_{n}]\ b} » renvoie « {f a_1(f a_2(\ldots,(f a_n b))} » |
Exercice 9. Réécrire la fonction « List.map2 : (‘a -> ‘b -> ‘c) -> ‘a list -> ‘b list -> ‘c list Rappel : « List.map2 f {[a_1 ; ... ; a_n]\;[b_1 ; ... ; b_n]} » renvoie « {[f\;a_1\;b_1;\ldots;f\;a_n\;b_n]}« . |
Exercice 10. Réécrire la fonction « List.iter2 : (‘a -> ‘b -> unit) -> ‘a list -> ‘b list -> ‘c list Rappel : « List.map2 f {[a_1 ; ... ; a_n]\;[b_1 ; ... ; b_n]} » effectue successivement « {f\;a_1\; b_1 ;\ldots; f a_n\; b_n}« . Les résultats sont perdus. On lève une exception si les longueurs sont différentes. |