(* ** Course: Concepts of Programming Languages (BU CAS CS 320) ** Semester: Summer I, 2009 ** Instructor: Hongwei Xi (hwxi AT cs DOT bu DOT edu) *) // // Assignment One (Due: Tuesday, May 26, 2009) // (* ****** ****** *) // Author: Hongwei Xi (hwxi AT cs DOT bu DOT edu) // Time: May, 2009 (* ****** ****** *) staload "assignment1.sats" (* ****** ****** *) // assgn1ex1 fn money_make (pound: int, shilling: int, pence: int): money = let val total = 240 * pound + 12 * shilling + pence val sgn = (if total >= 0 then 1 else ~1): int val total = sgn * total val pound = total / 240 val total = total - 240 * pound val shilling = total / 12 val pence = total - 12 * shilling in '{ pound= sgn * pound, shilling= sgn * shilling, pence= sgn * pence } end // end of [make] implement assgn1ex1_add (m1, m2) = let val pound = m1.pound + m2.pound val shilling = m1.shilling + m2.shilling val pence = m1.pence + m2.pence in money_make (pound, shilling, pence) end (* end of [assgn1ex_add] *) implement assgn1ex1_sub (m1, m2) = let val pound = m1.pound - m2.pound val shilling = m1.shilling - m2.shilling val pence = m1.pence - m2.pence in money_make (pound, shilling, pence) end (* end of [assgn1ex1_sub] *) (* ****** ****** *) // assgn1ex2 // [m] and [n] are assumed to be positive integers implement assgn1ex2_gcd (m, n) = let fun gcd (m: int, n: int): int = case+ 0 of | _ when m = n => m // GCD (m, m) = m | _ when m > n => gcd (n, m) // GCD (m, n) = GCD (n, m) | _ when (m mod 2 = 0) => begin if n mod 2 = 0 then 2 * gcd (m / 2, n / 2) else gcd (m / 2, n) end // end of [val] | _ (* m is odd *) => begin if n mod 2 = 0 then gcd (n / 2, m) else gcd ((n - m) / 2, m) end // end of [val] // end of [gcd] in gcd (m, n) end // end of [assgn1ex2_gcd] (* ****** ****** *) // assgn1ex3 implement assgn1ex3_P (n) = P (n) where { fun P (n: int): int = SP (n-1) and SP (n: int): int = // 1 + P(1) + ... + P (n) if n >= 1 then SP (n-1) + P (n) else 1 } (* ****** ****** *) // assgn1ex4 #include "assgn1ex4_solu.dats" (* ****** ****** *) // assgn1ex5 implement{a} list_last (xs) = ( let val- list0_cons (x, xs) = xs in loop (x, xs) end ) where { fun loop (x: a, xs: list0 a): a = case+ xs of | list0_cons (x, xs) => loop (x, xs) | list0_nil () => x // end of [loop] } // end of [list_last] (* ****** ****** *) // assgn1ex6 implement{a,b} listprod (xs, ys) = list0_reverse (res) where { typedef res_t = list0 @(a, b) fun loop1 (xs: list0 a, ys: list0 b, res: res_t): res_t = case+ xs of | list0_cons (x, xs) => let val res = loop2 (x, ys, res) in loop1 (xs, ys, res) end // end of [list0_cons] | list0_nil () => res // end of [loop1] and loop2 (x: a, ys: list0 b, res: res_t): res_t = case+ ys of | list0_cons (y, ys) => loop2 (x, ys, list0_cons ((x, y), res)) | list0_nil () => res // end of [loop2] val res = loop1 (xs, ys, list0_nil ()) } // end of [listprod] (* ****** ****** *) (* end of [assignment_solu.dats] *)