ML-使用异常时出错

时间:2016-12-29 19:47:53

标签: exception sml smlnj ml

如果我们得到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));

1 个答案:

答案 0 :(得分:1)

这是因为无法检查类型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));