(* CS 312 Problem Set 1 solutions *) (* Part 1: Post to cornell.test *) (***************************************************************************) (* Part 2: Style improvement *) (* a *) (* * If count is positive, append count dashes and a star to the base string. * Otherwise, append only a star. *) fun foo(count:int, base:string):string = if (count <= 0) then base ^ "*" else foo(count - 1, base ^ "-") (* b *) fun partB (p:bool, q:bool):bool = not p orelse q (* c *) fun fib (x:int):int = case x of 0 => 1 | 1 => 1 | _ => fib (x-1) + fib (x-2) (* d *) fun printFibs (x:int):unit = let val n = Int.toString x val fibN = Int.toString (fib x) in print ("The Fibonacci number at position " ^ n ^ " is " ^ fibN ^ ".\n" ^ fibN ^ " is my favorite number. Is " ^ fibN ^ " your favorite number too?") end (***************************************************************************) (* Part 3: `val' and `fun' declarations *) (* a *) val reallyCoolPeople = ("Ramin", "Tibor", "Siggi", "Hubert", "Abhishek", "Jackie", "Saikat", "Frances", "Kori", "Jeff", "Justin", "Tim", "Serge", "H", "Greg", "Jeff", "Walter", "Emmanuel") (* b *) val lastLetter = #"e" (* c *) val personal = {name="J. Random Hacker", age=42, cs=true} (* d *) fun cookingConversions (from:string, num:real, to:string):real = num * (case (from, to) of ("CUPS", "QUARTS") => 0.25000000 | ("CUPS", "LITERS") => 0.23658823 | ("QUARTS", "CUPS") => 4.00000000 | ("QUARTS", "LITERS") => 0.94635295 | ("LITERS", "CUPS") => 4.22675280 | ("LITERS", "QUARTS") => 1.05668820 | _ => 1.00000000) (* e *) fun gcd (j:int, k:int):int = case (j,k) of (0, _) => k | (_, 0) => j | _ => if (j = k) then j else case (j mod 2, k mod 2) of (0,0) => 2 * (gcd (j div 2, k div 2)) | (0,1) => gcd (j div 2, k) | (1,0) => gcd (j, k div 2) | _ => if j < k then gcd (k div 2 - j div 2, j) else gcd (k, j) (***************************************************************************) (* Part 4: The Standard Basis Library is your friend *) (* a *) fun isFifthCharUpper (s:string):bool = (String.size s >= 5) andalso (Char.isUpper (String.sub (s, 4))) (* b *) fun extractIntAndFraction (r:real):int*real = let val {whole=i, frac=f} = Real.split r in (Real.round i, f) end (* c *) fun currentTimeString ():string = Date.toString (Date.fromTimeLocal (Time.now ()))