(* an implementation of the factorial function using references *) letrec factorial: int -> int = let res = (ref 1: ref int) in letrec fact: int -> int = lam (n: int) => if n = 0 then !res else let _ = res := n * !res in fact (n-1) in fact in factorial (10) (* an example involving exception handling *) let prodfun = lam (f: int -> int) (n: int) => letrec aux: int -> int -> int = lam (i: int) (res: int) => if i = n then res else let x = f (i) in if x = 0 then raise Exit else aux (i+1) (x * res) in try aux 0 1 with Exit => 0 in prodfun (lam (n: int) => (n + 2) * (n - 3)) 10 (* finding perfect numbers *) let factorize = lam (x:int) => if x < 2 then (1, x) else (letrec g: int -> int * int = lam (y: int) => if y * y > x then (1, x) else if x mod y = 0 then (y, x / y) else g (y+1) in g (2)) in letrec sum_of_divisors: int -> int = lam (x: int) => let yz = factorize (x) in let y = yz.1 in let z = yz.2 in letrec aux: int -> int -> int * int = lam (Y: int) => lam (z: int) => if z mod y = 0 then aux (y * Y) (z / y) else ((y * Y - 1) / (y - 1), z) in if y = 1 then 1+z else let Yz = aux y z in Yz.1 * sum_of_divisors (Yz.2) in letrec perfect: int -> int = lam (x: int) => if sum_of_divisors (x) = x + x then x else perfect (x+1) in perfect (1000)