(********************************************************) (* chapitre 3 et chapitre 4 de Programmation fonctionnelle, générique et objet (Une introduction avec le langage OCaml) Ph. Narbel, Vuibert, 2005 Ces programmes ont pour but d'illustrer les sujets traités dans le livre. Il n'est donné aucune garantie quant à leur utilisation dans le cadre d'une activité professionnelle ou commerciale. Ces programmes peuvent être copiés sous reserve que leur provenance soit citée et que cet avertissement soit inclus. These programs are provided without warranty of any kind. Their purpose is just to serve as illustrations in the book. Permission to copy is granted provided that citation and this disclaimer of warranty are included. *) let relativ_mass (m, v) = let light_speed = 300000.0 *. 3600. in let ratio = v ** 2. /. light_speed ** 2. in m /. (sqrt (1. -. ratio));; let random_sequence (len, min, max) = let interv = max - min + 1 in let rec aux i = if i >= len then [] else ((Random.int interv) + min) :: aux (i + 1) in aux 0;; let string_of_int n = let dig n = Char.chr (n + Char.code '0') in let rec aux n = if n = 0 then "" else aux (n / 10) ^ Char.escaped (dig (n mod 10)) in aux n;; let pi_approx n_points = let dist x y = sqrt (x *. x +. y *. y) in let rec aux (m, n_points_in_disk) = if m <= 1 then n_points_in_disk else if dist (Random.float 1.) (Random.float 1.) <= 0.5 then aux (m - 1, n_points_in_disk + 1) else aux (m - 1, n_points_in_disk) in 16. *. (float_of_int (aux (n_points, 0)) /. (float_of_int n_points));; let approx_deriv f epsilon x = (f (x +. epsilon) -. f (x -. epsilon)) /. (2. *. epsilon);; let dderiv_approx f epsilon x = approx_deriv (approx_deriv f epsilon) epsilon x;; let rec sum f n0 n = if n < n0 then 0. else (f (float n)) +. (sum f n0 (n - 1));; let rec sum ~f ~n0 ~n = if n < n0 then 0. else (f (float n)) +. (sum ~f:f ~n0:n0 ~n:(n - 1));; let rec fib n = if n <= 0 then 0 else if n = 1 then 1 else fib (n - 1) + fib (n - 2);; let fib n = let rec aux m acc1 acc2 = if m = n then acc2 else aux (m + 1) acc2 (acc1 + acc2) in if n <= 0 then 0 else aux 1 0 1;;