From 4fa3783722515eb5a7656955b168c0022c2e77d4 Mon Sep 17 00:00:00 2001 From: Louis Date: Fri, 6 Oct 2023 14:26:13 +0200 Subject: [PATCH] vault backup: 2023-10-06 14:26:13 --- Algo/Courses/Chapter 6 - Lists (Exercises).md | 25 +++++++++++++------ 1 file changed, 18 insertions(+), 7 deletions(-) diff --git a/Algo/Courses/Chapter 6 - Lists (Exercises).md b/Algo/Courses/Chapter 6 - Lists (Exercises).md index 0572dec..2d8c5a7 100644 --- a/Algo/Courses/Chapter 6 - Lists (Exercises).md +++ b/Algo/Courses/Chapter 6 - Lists (Exercises).md @@ -1,13 +1,13 @@ ## 1.1 - Product ```Ocaml -let rec product = function +# let rec product = function | [] -> 0 | x::t -> x * product t;; ``` ## 1.2 - Count ```Ocaml -let rec count x n = +# let rec count x n = if x = [] then 0 else @@ -16,11 +16,16 @@ let rec count x n = 1 + count t n else 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 = ``` ## 1.3 - Search ```Ocaml -let rec search x n = +# let rec search x n = if x = [] then 0 else @@ -29,17 +34,23 @@ let rec search x n = true else 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 = ``` ## 1.4 - $n^{th}$ ```Ocaml -let rec length l = +# let rec length l = if l = [] then 0 else let e::t = l in 1 + length t;; -let rec nth x n = +# let rec nth x n = if (x = [] || n =< 0) then Invalid_arg "The number of element in the list is 0" else if length x < n then @@ -54,7 +65,7 @@ let rec nth x n = ## 1.5 - Maximum ```Ocaml -let rec max_value list = match list with +# let rec max_value list = match list with | [] -> failwith "La liste est vide" | [x] -> x | hd :: tl -> @@ -64,7 +75,7 @@ let rec max_value list = match list with ## 1.6 - Bonus second ```Ocaml -let rec second_smallest list = +# let rec second_smallest list = match list with | [] | [_] -> failwith "La liste ne contient pas au moins deux éléments distincts" | [x; y] -> if x < y then y else x