ML-Error in using exceptions

117 views Asked by At

I wrote a function for handling an exception if we got r2=0 and i2=0, but when I run the program I get this error:

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

Here is my code:

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

There are 1 answers

3
IonuČ› G. Stan On BEST ANSWER

It happens because values of type real can't be checked for equality with the normal = operator. This happens due to how floating-point numbers are represented inside a computer and, honestly, it's something I can't explain to someone else yet. However, the solution is simple. You have to use the Real.== equality operator:

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));