Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert Real to Int?

Tags:

sml

smlnj

Let's say I have 0.0 how do I convert it to 0?

I know that I can use Real.fromInt(0) to do the opposite (0 -> 0.0) but what about Real to Int?

In the SML documentation I read about a function toInt, but there was no example so I probably use it in the wrong way.

I tried this:

Real.toInt(a)
val a Real.toInt;

Both are wrong...

like image 666
tonythestark Avatar asked Sep 05 '25 03:09

tonythestark


1 Answers

Real.toInt has type IEEEReal.rounding_mode -> real -> int so it requires that you specify a rounding mode. For example:

Real.toInt IEEEReal.TO_NEAREST 1.2;

evaluates to 1.

There is almost no reason to use Real.toInt in everyday programming. Instead, just use one of round, floor, ceil, trunc -- functions which correspond to the 4 rounding modes of TO_NEAREST, TO_NEGINF, TO_POSINF, TO_ZERO respectively. In other words, rather than use Real.toInt IEEEReal.TO_NEAREST 1.2, just use round 1.2. Of the four functions, trunc corresponds to how int() works in Python (and other languages), so is probably the most familiar one.

The only time that I can see for using Real.toInt is if you want to experiment with how different rounding modes affect a calculation. Unless you use a variable for the rounding mode which takes on different values in different calls, it is more readable to use one of the four conversion functions which have a hard-wired rounding mode.

like image 52
John Coleman Avatar answered Sep 07 '25 22:09

John Coleman