Search code examples
ml

operator and operand don't agree error in this simple function


Consider this definition:

fun abs(x:int):int = (x*x)/(~x);

which should return the absolute value of the input. But when the function is called, I get this error:

Error: operator and operand don't agree [tycon mismatch]
  operator domain: real * real
  operand:         int * int
  in expression:
    x * x / ~ x

What am I doing wrong? Didn't I use :intcorrectly?

Thanks


Solution

  • In SML, / is division on reals. For integers, you need to use div.

    > fun abs x = x*x div ~x;
    val abs = fn : int -> int