vault backup: 2023-10-06 14:26:13

This commit is contained in:
Louis Gallet 2023-10-06 14:26:13 +02:00
parent 0b9230c8cb
commit 4fa3783722
Signed by: lgallet
SSH Key Fingerprint: SHA256:qnW7pk4EoMRR0UftZLZQKSMUImbEFsiruLC7jbCHJAY

View File

@ -1,13 +1,13 @@
## 1.1 - Product ## 1.1 - Product
```Ocaml ```Ocaml
let rec product = function # let rec product = function
| [] -> 0 | [] -> 0
| x::t -> x * product t;; | x::t -> x * product t;;
``` ```
## 1.2 - Count ## 1.2 - Count
```Ocaml ```Ocaml
let rec count x n = # let rec count x n =
if x = [] then if x = [] then
0 0
else else
@ -16,11 +16,16 @@ let rec count x n =
1 + count t n 1 + count t n
else else
count t n;; count t n;;
(* Correction *)
# let rec count x = function
| [] -> 0
| e::t -> (if x = e then 1 else 0) + count x t;;
val count = 'a -> 'a list -> int = <fun>
``` ```
## 1.3 - Search ## 1.3 - Search
```Ocaml ```Ocaml
let rec search x n = # let rec search x n =
if x = [] then if x = [] then
0 0
else else
@ -29,17 +34,23 @@ let rec search x n =
true true
else else
search t n;; search t n;;
(* Correction *)
# let search x = function
| [] -> false
| e::t when x = e -> true
| _::t -> search x t ;;
val search 'a -> 'a list -> bool = <fun>
``` ```
## 1.4 - $n^{th}$ ## 1.4 - $n^{th}$
```Ocaml ```Ocaml
let rec length l = # let rec length l =
if l = [] then if l = [] then
0 0
else else
let e::t = l in let e::t = l in
1 + length t;; 1 + length t;;
let rec nth x n = # let rec nth x n =
if (x = [] || n =< 0) then if (x = [] || n =< 0) then
Invalid_arg "The number of element in the list is 0" Invalid_arg "The number of element in the list is 0"
else if length x < n then else if length x < n then
@ -54,7 +65,7 @@ let rec nth x n =
## 1.5 - Maximum ## 1.5 - Maximum
```Ocaml ```Ocaml
let rec max_value list = match list with # let rec max_value list = match list with
| [] -> failwith "La liste est vide" | [] -> failwith "La liste est vide"
| [x] -> x | [x] -> x
| hd :: tl -> | hd :: tl ->
@ -64,7 +75,7 @@ let rec max_value list = match list with
## 1.6 - Bonus second ## 1.6 - Bonus second
```Ocaml ```Ocaml
let rec second_smallest list = # let rec second_smallest list =
match list with match list with
| [] | [_] -> failwith "La liste ne contient pas au moins deux éléments distincts" | [] | [_] -> failwith "La liste ne contient pas au moins deux éléments distincts"
| [x; y] -> if x < y then y else x | [x; y] -> if x < y then y else x