-- Ex 1.1 -------------------------------------------------------------------- let solutions a b c = let delta = (b *. b) -. (4.0 *. a *.c) in if delta < 0.0 then [] else if delta > 0.0 then let s = sqrt(delta) in [ (-. b -. s) /. (2.0 *. a); (-. b +. s) /. (2.0 *. a) ] else [ -.b /. (2. *. a) ] ;; (* In order to verify that computed solutions give results that are close to 0 *) let verify a b c = match solutions a b c with [] -> [] | [r] -> [ a *. (r *. r) +. b *. r +. c ] | [r1;r2] -> [ a *. (r1 *. r1) +. b *. r1 +. c; a *. (r2 *. r2) +. b *. r2 +. c ] | _ -> failwith "impossible" ;; -- Ex 1.2 -------------------------------------------------------------------- let deriv f x dx = (f(x+.dx) -. f(x)) /. dx ;; -- Ex 1.3 -------------------------------------------------------------------- let smooth f dx = fun x -> (f(x) +. f(x -. dx) +. f(x +. dx)) /. 3.0 ;; -- Ex 1.4 -------------------------------------------------------------------- (* We assume that the parameter n is never negative. Without that assumption, we should add a test. *) let rec power_lin a n = match n with 0 -> 1.0 | n -> a *. (power_lin a (n-1)) ;; (* power_lin is linear in the argument n: it involves exactly n multiplications *) let rec power_log a n = match n with 0 -> 1.0 | n -> let m = n/2 in let p = power_log a m in (match n mod 2 with 0 -> p *. p | _ -> a *. p *. p) ;; (* power_log is logarithmic: for an argument n, it computes power_log a (n/2) only once, and performs at most 2 other multiplications. Therefore, the number of multiplications is smaller that 2*log2(n) *) -- Ex 1.5 -------------------------------------------------------------------- let rec euclid_gcd m n = match (m,n) with (0, n) -> n | (m, 0) -> m | _ -> if m > n then euclid_gcd (m-n) m else euclid_gcd m (n-m) ;; -- Ex 1.6 -------------------------------------------------------------------- let prime n = if n < 4 then true else let rec prec n d = if d < n then match n mod d with 0 -> false | _ -> prec n (d+1) else true in prec n 2 ;; -- Ex 1.7 -------------------------------------------------------------------- let or3 a b c = match (a,b,c) with (true, _, _) -> true | (_, true, _) -> true |(_, _, b) -> b ;; -- Ex 1.8 -------------------------------------------------------------------- (* The f parameter is applied to x and y. Therefore, f is a function from A to B, and x and y both belong to A. The resulting pair is of type (B * B). Written the Caml way, we obtain: *) (fun f -> fun (x,y) -> (f x, f y)) : ('a -> 'b) -> 'a * 'a -> 'b * 'b