7
votes

I'm new to SML, and am using the SMLNJ dialect.

For some purpose I have been trying to typecast 3 to 3.0 (int to real).

Could not find a way out. How can I do this? How can I convert between types?

2
Nevermind, I found the answer. You just type real(2) for instance, to convert 2 (int) to 2.0 (real).Dave

2 Answers

14
votes

You can use the function real (or Real.fromInt) to convert an int to a real.

For further information you can see a list of functions available in the Top-level environment here and an overview of the Basis library here.

7
votes

SML doesn't have typecasts. Any mapping between types needs to be done through functions.

real(3) looks and behaves much like a C-style typecast, but real: int -> real is just another function in the standard basis. int(3.0), on the other hand, doesn't work, because the int function doesn't exist.

In general, when you need to convert between types, you'd just dig through the library for an appropriate function. In the real -> int case, just searching for "real -> int" in the top level environment turns up round, trunc, floor and ceil.