mp2i-info/tp6/lib/lib.ml
2025-12-04 19:49:12 +01:00

128 lines
2.7 KiB
OCaml

type nombre =
Entier of int |
Flottant of float |
Fraction of int * int |
Moins_inf |
Plus_inf;;
(* Exercice 1 *)
let correct n = match n with
| Fraction(_, q) -> q > 0
| _ -> true
;;
(* Exercice 2 *)
let rec ( $= ) a b = match a, b with
| Fraction(a, b), Fraction(c, d) -> a*d = b*c
| Entier a, Entier b -> a = b
| Flottant a, Flottant b -> a = b
| Entier a, Flottant b -> float_of_int a = b
| Entier a, Fraction(b, c) -> c*a = b
| Flottant a, Fraction(b, c) -> a = (float_of_int b) /. (float_of_int c)
| (Moins_inf | Plus_inf), _ -> false
| a, b -> b $= a
;;
(* Exercice 3 *)
let rec ( $< ) a b = match a, b with
| Fraction(a, b), Fraction(c, d) -> a*d < b*c
| Entier a, Entier b -> a < b
| Flottant a, Flottant b -> a < b
| Entier a, Flottant b -> float_of_int a < b
| Entier a, Fraction(b, c) -> c*a < b
| Flottant a, Fraction(b, c) -> a < (float_of_int b) /. (float_of_int c)
| Moins_inf, Moins_inf -> false
| Moins_inf, _ -> true
| Plus_inf, Plus_inf -> false
| _, Plus_inf -> true
| a, b -> b $< a
;;
(* Exercice 4 *)
let rec ($+) a b = match a, b with
| Fraction(a, b), Fraction(c, d) -> Fraction(a*d + b*c, b*d)
| Entier a, Entier b -> Entier(a + b)
| Flottant a, Flottant b -> Flottant(a +. b)
| Entier a, Flottant b -> Flottant(float_of_int a +. b)
| Entier a, Fraction(b, c) -> Fraction(a*c + b, c)
| Flottant a, Fraction(b, c) -> Flottant(a +. ((float_of_int b) /. (float_of_int c)))
| Moins_inf, Plus_inf -> failwith "Cannot add -infinity and +infinity"
| Moins_inf, _ -> Moins_inf
| _, Plus_inf -> Plus_inf
| a, b -> b $+ a
;;
(* Exercice 5 *)
type valeur = Sept | Huit | Neuf | Dix | Valet | Dame | Roi | As;;
type couleur = Trefle | Pique | Coeur | Carreau;;
type carte = { va : valeur; coul : couleur };;
let coul_i c = match c with
| Trefle -> 0
| Pique -> 1
| Coeur -> 2
| Carreau -> 3
;;
let count_coul hand = Array.fold_left
(fun acc x ->
let () = acc.(coul_i x.coul) <- acc.(coul_i x.coul)+1 in
acc
)
[|0;0;0;0|]
hand
;;
(* Exercice 6 *)
let points_carte carte = match carte.va with
| As -> 11
| Dix -> 10
| Roi -> 4
| Dame -> 3
| Valet -> 2
| _ -> 0;;
let hand_points hand = Array.fold_left
(fun acc x ->
acc + points_carte x
)
0
hand
;;
(* Exercice 7 *)
let val_i v = match v with
| Sept -> 0
| Huit -> 1
| Neuf -> 2
| Dix -> 3
| Valet -> 4
| Dame -> 5
| Roi -> 6
| As -> 7
;;
let count_val hand = Array.fold_left
(fun acc x ->
let () = acc.(val_i x.va) <- acc.(val_i x.va)+1 in
acc
)
[|0;0;0;0;0;0;0;0|]
hand
;;
(* Exercice 8 *)
let has_series hand = (
Array.fold_left
(fun acc x ->
if x = 0 && acc < 5 then
0
else
acc + 1
)
0
(count_val hand)
) >= 5
;;