CS 334
|
Please do problem 6.29a,b on pages 6-52 and 6-53.
Please read about applicative and normal-order evaluation in Chapter 7 of Louden and do problem 7.14 on page 7-32.
"if true then first else second" is equivalent to evaluating "first",
"if false then first else second" is equivalent to evaluating "second".
Suppose we define the function cond in ML as follows:
fun cond boolval first second = if boolval then first else second;
a. Find expressions for first and second so that cond true first second is not equivalent to first.
b. Find expressions for first and second so that cond false first second is not equivalent to second. Hint: The answers to (a) and (b) are similar -- and yes, it IS a trick question!
c. Explain the different results in terms of eager (applicative) and lazy (normal order) evaluation.
fun char_to_num c = ord c - ord #"0"; fun calc_list ([],n) = n | calc_list ((fst::rest),n) = calc_list(rest,10 * n + char_to_num fst); fun string_to_num s = calc_list(explode s, 0);For instance, string_to_num "3405" returns the integer, 3405. Unfortunately, calc_list returns a spurious result if the string contains any non-digits. For instance, string_to_num "3a05" returns 7905, while string_to_num " 405" returns ~15595. This occurs because char_to_num will convert any character, not just digits. We can attempt to fix this by having char_to_num raise an exception if it is applied to a non-digit.
a. Please revise the definition of char_to_num to raise this exception, and then modify the function string_to_num so that it handles the exception, returning ~1 if there is a non-digit in the string. You should make no changes to calc_list.
b. Please rewrite these ML functions to provide the same behavior (including returning ~1 if the string includes a non-digit) as in (a), but without using exceptions. While you may change any function, try to preserve as much of the structure of the original program as possible.