 ## CS 334 Programming Languages Spring 2002 Assignment 5 Due Friday (really!), 3/15/2002

1. Please do problem 6.29a,b on pages 6-52 and 6-53.

2. Please read about applicative and normal-order evaluation in Chapter 7 of Louden and do problem 7.14 on page 7-32.

3. The "if ... then ... else ..." construct in ML satisfies the following rules for all expressions first and second:
• "if true then first else second" is equivalent to evaluating "first",

• "if false then first else second" is equivalent to evaluating "second".

Where expressions e1 and e2 are equivalent iff either both are undefined or both are defined and have the same value.

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.

4. The function string_to_num defined below uses two auxiliary functions to convert a string of digits into a non-negative integer.
```   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.

Back to: