Functional Programming & Proofs


Trees and languages

  1. (functions, types'synonyms and unions) How to compute the area of a circle in F# ?
    What is the area of a circle having radius equals to 2 ?
    Define pi, the area function and the real numbers' type.
    Also explain how to deal with expression such as area (-1) ; e. how to model "errors" ?
let pi     = 3.1415;;
let area r = pi*r*r;;
area 2.0;;

type real = float;;
let area : real -> real = fun r -> pi*r**2;;
area 2.0;; 

area (-1);;
type ResultOrError = Error | Result of real;;
let area : real -> ResultOrError = 
  fun r -> if (r>0) then Result (pi*r**2) else Error;;
area (-1);;

type 't ResultOrError = Error | Result of 't;;
let area : real -> real ResultOrError = 
  fun r -> if (r>0) then Result (pi*r**2) else Error;;

area (-1), area 2;;

2 - 10