(* tuples *) let x = (3, "hi", true) (* let *) let z = 3 (* uncurried *) let longEnough (str, len) = String.length str >= len (* curried *) let longEnough str len = String.length str >= len (* anonymous functions *) let square x = x * x let square = fun x -> x * x (* higher order functions and values *) let twice f = fun x -> f (f x) let twice f x = f (f x) let fourth = twice square let fourth = twice (fun x -> x * x) (* let rec and embedded lets *) let isPrime (n : int) : bool = (* Returns true if n has no divisors between m and sqrt(n) inclusive. *) let rec noDivisors (m : int) : bool = m * m > n || (n mod m != 0 && noDivisors (m + 1)) in n >= 2 && noDivisors 2 (* Computes the square root of x using Heron of Alexandria's * algorithm (circa 100 AD). We start with an initial (poor) * approximate answer that the square root is 1.0 and then * continue improving the guess until we're within delta of the * real answer. The improvement is achieved by averaging the * current guess with x/guess. The answer is accurate to within * delta = 0.0001. *) let squareRoot (x : float) : float = (* numerical accuracy *) let delta = 0.0001 in (* returns true iff the guess is good enough *) let goodEnough (guess : float) : bool = abs_float (guess *. guess -. x) < delta in (* return a better guess by averaging it with x/guess *) let improve (guess : float) : float = (guess +. x /. guess) /. 2.0 in (* Return the square root of x, starting from an initial guess. *) let rec tryGuess (guess : float) : float = if goodEnough guess then guess else tryGuess (improve guess) in (* start with a guess of 1.0 *) tryGuess 1.0