Reputation: 1733
I am new to ML.
I need to define a function taking an conditional expression as argument, the problem is if the expression is invalid like "10 div 0 = 0"
. How can I handle this?
For example, the function is defined as following: foo exp1 = if (exp1) then ... else...
, and exp1
is "10 div 0 = 0"
, how to handle this division error.
Upvotes: 4
Views: 2888
Reputation: 41290
It looks like you want to ask about exception handling mechanism in SML.
The div
function in SML basis library raise Div exception when you invoke 10 div 0
. It depends on whether you need the value or not to handle the exception. You can either return true/false or option type in this case:
(* only catch exception, ignore value *)
fun div_check (x, y) = (
ignore (x div y);
false
) handle Div => true
(* catch exception and return option value *)
fun div_check2 (x, y) = (
SOME (x div y)
) handle Div => NONE
UPDATE:
It is really weird that the compiler doesn't raise Div
exception in this case. I suggest that you define a custom div function and raise/handle exceptions yourself:
exception DivByZero;
(* custom div function: raise DivByZero if y is zero *)
infix my_div;
fun x my_div y =
if y=0 then raise DivByZero else x div y
fun div_check (x, y) = (
ignore (x my_div y);
false
) handle DivByZero => true
fun div_check2 (x, y) = (
SOME (x my_div y)
) handle DivByZero => NONE
Upvotes: 4