(* Lecture 3 *) (* requires: y>=0 *) (* returns: x to the power of y *) let rec pow ((x : int), (y : int)) : int = if y=0 then 1 else x * pow(x,y-1) let cube (x : int) : int = pow (x,3) let sixtyfour = cube 4 let fortytwo = pow(2,4) + pow(4,2) + cube(2) + 2 let isPrime (n : int) : bool = (* returns: whether 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 (* returns: an approximate square root of x. The return value * 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, * 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. *) 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 let abs1 (x : int) : int = if x<0 then -x else x let abs2 : int -> int = function x -> if x<0 then -x else x let abs3 : int -> int = fun x -> if x<0 then -x else x type day = Sun | Mon | Tue | Wed | Thu | Fri | Sat (* returns: the day of the week for d *) let day_to_int (d : day) = if d=Sun then 1 else if d=Mon then 2 else if d=Tue then 3 else if d=Wed then 4 else if d=Thu then 5 else if d=Fri then 6 else (* d=Sat *) 7 let day_to_int (d : day) = match d with Sun -> 1 | Mon -> 2 | Tue -> 3 | Wed -> 4 | Thu -> 5 | Fri -> 6 | Sat -> 7 type time = {hour: int; min: int; ampm: string} let best_time = {hour = 10; min = 10; ampm = "am"} let ten = best_time.hour let sum_triple (triple:int*int*int) = let (x, y, z) = triple in x + y + z type stooges = {larry:int; moe:int; curly:int} let sum_stooges (s:stooges) = let {larry=x; moe=y; curly=z} = s in x + y + z