|
CS 334
|
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.
When you evaluate a function call (with a user-defined function), you should not evaluate the parameter, instead package the (unevaluated) actual parameter and the current environment into a NameThunk and insert it into the environment in the same way that you used to insert the value of the actual parameter into the environment. Make sure that the THUNK is handled properly when its value is needed. (Hint: Depending on how you handled THUNK's before you may not need to make any changes to that part of your code.)
abstype 'a stack = mkstack of ('a list)
with exception stackUnderflow
val emptyStk : 'a stack = mkstack []
fun push (e:'a) (mkstack(s):'a stack) = mkstack(e::s)
fun pop (mkstack([]):'a stack) = raise stackUnderflow
| pop (mkstack(e::s):'a stack) = mkstack(s):'a stack
fun top (mkstack([]):'a stack) = raise stackUnderflow
| top (mkstack(e::s):'a stack) = e
fun IsEmpty (mkstack([]):'a stack) = true
| IsEmpty (mkstack(e::s):'a stack) = false
end;