mp2i-info/tp4/tp4.ml
2026-01-13 23:28:06 +01:00

61 lines
1.3 KiB
OCaml

(* Exercice 1 *)
let rec somme_liste l = match l with
| [] -> 0
| a::q -> a + somme_liste q;;
let rec taille_liste l = match l with
| [] -> 0
| _::q -> 1 + taille_liste q;;
let rec pow valeur exposant = match exposant with
| 0 -> 1
| i -> valeur * (pow valeur (i - 1));;
(* 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));;
let rec est_dans_liste element l = match l with
| [] -> false
| a::q -> a = element || est_dans_liste element q;;
(* Exercice 2 *)
let biggest l = match l with
| [] -> failwith "Empty list"
| x::q -> List.fold_left
(fun acc a -> max acc a)
x
q
;;
(* Exercice 3 *)
let prod l = List.fold_left (fun acc x -> acc *. x) 1. l;;
(* Exercice 4 *)
let rec is_ordered l = match l with
| a::(b::q) -> a <= b && is_ordered (b::q)
| _ -> true
;;
(* 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;;