(* Exercice 1 *) let rec somme_liste l = match l with | [] -> 0 | a::q -> a + somme_liste q;; assert (somme_liste [1; 3; 2] = 6);; let rec taille_liste l = match l with | [] -> 0 | _::q -> 1 + taille_liste q;; assert (taille_liste [1; 3; 2] = 3);; let rec pow valeur exposant = match exposant with | 0 -> 1 | i -> valeur * (pow valeur (i - 1));; assert (pow 4 3 = 64);; (* On peut remplacer i - 1 par exposant - 1 car les deux noms coexistent. *) let rec part_ent_log2 nombre = if nombre = 0 then failwith "Boum !"; (* Il est toujours utile de connaître les exceptions tôt. *) if nombre = 1 then 0 else 1 + (part_ent_log2 (nombre / 2));; assert (part_ent_log2 10 = 3);; let rec est_dans_liste element l = match l with | [] -> false | a::q -> a = element || est_dans_liste element q;; assert (est_dans_liste 2 [1; 3; 2]);; assert (not (est_dans_liste 4 [1; 3; 2]));; (* Exercice 2 *) let biggest l = match l with | [] -> failwith "Empty list" | x::q -> List.fold_left (fun acc a -> max acc a) x q ;; assert (biggest [0; 7; 4] == 7);; (* Exercice 3 *) let prod l = List.fold_left (fun acc x -> acc *. x) 1. l;; assert (abs_float (prod [1.5; 2.; 3.] -. 9.) <= 1e-14 );; (* Exercice 4 *) let rec is_ordered l = match l with | a::(b::q) -> a <= b && is_ordered (b::q) | _ -> true ;; assert (is_ordered [1; 5; 6]);; assert (not (is_ordered [5.6; 7.8; 3.]));; (* Exercice 5 *) let rec is_rev_ordered l = match l with | a::b::q -> a >= b && is_rev_ordered (b::q) | _ -> true ;; let rec has_ordering l = match l with | a::b::q -> if a < b then is_ordered (b::q) else if a > b then is_rev_ordered (b::q) else has_ordering (b::q) | _ -> true;; assert (has_ordering [1; 1; 2; 2; 3]);; assert (has_ordering [3; 2; 1; 1]);; assert (not (has_ordering [1; 1; 2; 1]));;