Search code examples
floating-pointintegertype-conversionsml

Can't unify IEEEReal.rounding_mode with real


Why do I get an error when I try to convert a real to an int like this?

fun stuff a  =
  Real.toInt a

Error:

Error-Can't unify IEEEReal.rounding_mode with real (Different type constructors) Found near stuff
(0.0)

Solution

  • Perhaps you overlooked that Real.toInt : IEEEReal.rounding_mode -> real -> int, i.e. takes an additional argument that specifies how rounding is made. In case you don't want to specify this extra argument, e.g. like

    fun round x = Real.toInt IEEEReal.TO_NEAREST x
    

    you could use one of the functions

    • Real.floor : real -> int which assumes IEEEReal.TO_NEGINF,
    • Real.ceil : real -> int which assumes IEEEReal.TO_POSINF,
    • Real.trunc : real -> int which assumes IEEEReal.TO_ZERO, or
    • Real.round : real -> int which assumes IEEEReal.TO_NEAREST.

    Fun fact: The function Real.toInt is actually defined in terms of these four functions.