ML-错误使用异常

ML-Error in using exceptions

如果我们得到 r2=0 和 i2=0,我写了一个处理异常的函数,但是当我 运行 程序时我得到这个错误:

operatii.ml:12: error: Type error in function application.
   Function: = : ''a * ''a -> bool
   Argument: (r2, 0.0) : real * real
   Reason: Can't unify ''a to real (Requires equality type)
Found near
  if r2 = 0.0 then raise ImpartitorulEsteNul else
  (
     (r2 * r1 - i1 * i2) / (r2 * r2 + i1 * i2),
     (... * ... + ... * ...) / (... * ... + ... * ...)
     )
Exception- Fail "Static Errors" raised

这是我的代码:

infix %%%%;
exception ImpartitorulEsteNul;
fun (r1,i1) %%%% (r2:real,i2:real)=if r2=0.0 andalso i2=0.0 then raise ImpartitorulEsteNul
                         else ((r2*r1-i1*i2)/(r2*r2+i1*i2),(r2*i1+i1*i2)/(r2*r2+i1*i2));

这是因为 real 类型的值无法用普通的 = 运算符检查是否相等。发生这种情况是由于浮点数在计算机中的表示方式,老实说,这是我还无法向其他人解释的事情。但是,解决方案很简单。您必须使用 Real.== 相等运算符:

infix %%%%;

infix ==;

(* Import just the == function from the Real structure. *)
(* I hope you can make sense out of this line. *)
val op == = Real.==;

exception ImpartitorulEsteNul;

fun (r1,i1) %%%% (r2:real,i2:real) =
  if r2==0.0 andalso i2==0.0
  then raise ImpartitorulEsteNul
  else ((r2*r1-i1*i2)/(r2*r2+i1*i2),(r2*i1+i1*i2)/(r2*r2+i1*i2));