Solution Ocaml
Solution Ocaml
let fibTail n =
let rec aux n a b =
match n with
| 0 -> a
| _ -> aux (n - 1) b (a + b)
in aux n 0 1
;;
fib 42;;
fibTail 42;;
(* task 2 *)
let root3 a =
let precision = 1e-15 in
let rec aux x =
if abs_float (x *. x *. x -. a) <= precision *. abs_float a then x
else aux(x +. (a /. (x *. x) -. x) /. 3.)
in aux (if a > 1. then a /. 3. else a)
;;
root3 (-216.);;
(* task 3 *)
let [_; _; x; _; _] = [-2; -1; 0; 1; 2];;
let [(_, _); (x, _)] = [(1, 2); (0, 1)];;
(* task 4 *)
let rec initSegment (xs, ys) =
match (xs, ys) with
| ([], _) -> true
| (_, []) -> false
| (x_head :: x_tail, y_head :: y_tail) ->
if x_head = y_head then initSegment (x_tail, y_tail)
else false
;;
(* task 5 *)
let rec replaceNth list n x =
match (list, n) with
| ([], _) -> []
| (_ :: tl, 0) -> x :: tl
| (hd :: tl, _) -> hd :: replaceNth tl (n - 1) x
;;