let x = 1 ;;
let y = 2 ;;
let y = x+1 ;;
y ;;
let x = 10 ;;
y ;;
let a = 2 and b = a+1 ;;
This does not work because $\texttt{a}$ is not in the context where $\texttt{b}$ is computed.
let x = 4 in x * x ;;
let a = 2 in a + 1 ;;
let term1 = 10 and term2 = 0 in term1 * term2;;
let a = 1 in let b = a+1 in let c = a+b in let d = a+b+c in d ;;
let a = 10 and b = 3 and c = 5 ;; (* we need to define three identifiers a, b and c for the next expression *)
let discriminant = b*b - 4*a*c in
if discriminant > 0 then 2
else if discriminant = 0 then 1
else 0 ;;
let e = let prod = 4*3*2 in prod*prod+prod+2 ;;
fun x -> x ;;
As you can notice the type of this function is $\texttt{'a -> 'a}$ which is $\texttt{any_type -> any_type}$ (note that the "departure type" and the "arriving" type should be the same - it can be any type. We say that this function is polymorphic -- as we shall see later in the lecture.
Below are three equivalent anonymous functions computing the absolute value.
fun a ->
if a < 0 then -a
else a;;
function a ->
if a < 0 then -a
else a ;;
fun (a:int) ->
if a < 0 then -a
else a ;;
Below are several equivalent ways to define the identy function (except that some are polymorphic). Remember that we choose to explicitely mention the parameter's types and the result type.
let identity = function x -> x ;;
let identity = fun x -> x ;;
let identity = function (x:int) -> x ;;
let identity = fun (x:int) -> x ;;
let identity x = x ;;
let identity (x:int):int = x ;;
Note that explicitely indicating the type does not forbid to be polymorphic as demonstrated by the function below.
let identity (x:'a):'a = x ;;
let is_zero (x:int): bool = x=0 ;;
let successor (x:int):int = x+1 ;;
let surface (length:float) (width:float):float = length *.width ;;
let surface_circle (radius:float):float =
let pi = 3.14 in pi *. (radius**2.);;
identity x ;;
identity (x) ;;
(fun (x:int) -> x+1) 3 ;;
surface_circle 9.76 ;;
let successor2 (x:int):int=x+1 in successor2 10 ;;
The command below shows that $\texttt{successor2}$ is not available globally
successor2 19 ;;
let discriminant (a : int) (b : int) (c : int):int = b * b - 4 * a * c ;;
discriminant 2 3 4 ;;