```(*
** Course: Concepts of Programming Languages (BU CAS CS 320)
** Semester: Summer I, 2009
** Instructor: Hongwei Xi (hwxi AT cs DOT bu DOT edu)
*)

//
// Author: Hongwei Xi (hwxi AT cs DOT bu DOT edu)
// Time: May 20, 2009
//

(* ****** ****** *)

// [exponent] should be a natural number
extern fun power1 (base: double, exponent: int): double
extern fun power2 (base: double, exponent: int): double

implement power1 (b, n) = // non-tail-recursive
if n >= 2 then let
val n2 = n / 2
in
if n = n2 + n2 then power1 (b * b, n2) else b * power1 (b * b, n2)
end else begin
if n = 1 then b else 1.0
end (* end of [if] *)
// end of [power1]

implement power2 (b, n) = let // tail-recursive
fun loop (b: double, n: int, res: double): double =
if n >= 2 then let
val n2 = n / 2
in
if n = n2 + n2 then
loop (b * b, n2, res)
else
loop (b * b, n2, b * res)
// end of [if]
end else begin
if n = 1 then b * res else res
end // end of [if]
in
loop (b, n, 1.0)
end // end of [power2]

(* ****** ****** *)

// some functions handling characters

val char_a = 'a' and char_A = 'A'

fun isLower (c: char): bool =
if c >= 'a' andalso c <= 'z' then true else false

fun isUpper (c: char): bool =
if c >= 'A' andalso c <= 'Z' then true else false

fun digit_of_int (i: int): char = char_of_int (int_of_char '0' + i)

fun xdigit_of_int (i: int): char = begin
if i <= 9 then char_of_int (int_of_char '0' + i) else char_of_int (int_of_char 'a' + i - 10)
end // end of [xdigit_of_int]

fun title_append (name: string): string = "The Duke of " + name

(* ****** ****** *)

typedef intlst = list0 (int)

fun is_nil (xs: intlst): bool =
case xs of
| list0_nil () => true
| list0_cons _ => false
// end of [is_nil]

fun is_cons (xs: intlst): bool =
case xs of
| list0_nil () => false
| list0_cons _ => true
// end of [is_cons]

// [length1] is non-tail-recursive
fun length1 (xs: intlst): int = case xs of
| list0_nil () => 0
| list0_cons (_, xs1) => 1 + length1 (xs1)
// end of [length1]

fun length2 // [length2] is tail-recursive
(xs: intlst): int = loop (xs, 0) where {
fun loop (xs: intlst, res: int): int = case xs of
| list0_nil () => res
| list0_cons (_, xs1) => loop (xs1, res + 1)
} // end of [length2]

(* ****** ****** *)

(* end of [code-2009-05-20.dats] *)

```