Functional Programming & Proofs


Introduction (2): Functional Programming

  1. Control flow with ifThenElse
let abs (x:float):float = if x<0 then -x else x;;
abs -3;; // 3.0

NB. another possibility is tu use "Pattern Matching"

let abs (x:float):float = 
 match x<0 with
 | true  -> -x
 | false -> x;;
  1. Loops are defined with recursion
let rec solve f a b = 
 let c = (a+b)/2.0
 if abs (f c) <0.01 then c else
  if (f a)*(f c)<0 then solve f a c else solve f c b;;

solve g -2 0; // -0.5
g -0.5;; // 0.01
f -0.5;; // -0.25 optimum

Info. The preceding code gives an implementation of the bissection method (see also binary search).


5 - 8