How to handle division by zero error in ML

I am new to ML.

I need to define a function that takes a conditional expression as an argument, the problem is that the expression is not valid, for example "10 div 0 = 0" . How can I handle this?

For example, a function is defined as follows: foo exp1 = if (exp1) then ... else... , and exp1 - "10 div 0 = 0" , how to handle this separation error.

+4
source share
1 answer

It sounds like you want to ask about the exception handling mechanism in SML.

The div function in the SML core library raises the Div exception when calling 10 div 0 . It depends on whether you need a value or not to handle the exception. You can either return true / false, or the 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 very strange that in this case the compiler does not throw a div exception. I suggest you define a custom div function and call / 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 
+4
source

Source: https://habr.com/ru/post/1384929/


All Articles