epicours/Algo/Courses/Chapter 6 - Lists (Exercises).md

1.6 KiB

1.1 - Product

let rec product = function
	| [] -> 0
	| x::t -> x * product t;;

1.2 - Count

let rec count x n =
	if x = [] then
		0
	else
		let e::t = x in
		if e = x then
			1 + count t n
		else
			count t n;;
let rec search x n =
	if x = [] then
		0
	else
		let e::t = x in
		if e = x then
			true
		else
			search t n;;

1.4 - n^{th}

let rec length l = 
	if l = [] then
		0
	else
		let e::t = l in
			1 + length t;;
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
		Failwith "The list is too short"
	else
		let e::t = x in
		if n = 0
			return e
		else
			nth t (n-1) ;;

1.5 - Maximum

let rec max_value list = match list with 
	| [] -> failwith "La liste est vide" 
	| [x] -> x 
	| hd :: tl -> 
		let max_tail = max_value tl in 
		if hd > max_tail then hd else max_tail;;

1.6 - Bonus second

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
  | hd1 :: hd2 :: tl ->
    let min1, min2 =
      if hd1 < hd2 then (hd1, hd2) else (hd2, hd1)
    in
    let rec find_second_smallest rest =
      match rest with
      | [] -> min2
      | hd :: tl ->
        if hd < min1 then find_second_smallest (min1 :: tl)
        else if hd < min2 && hd > min1 then find_second_smallest (hd :: min1 :: tl)
        else find_second_smallest (min2 :: tl)
    in
    find_second_smallest tl