In an attempt to create an interpreter for a simple language in SML, I am struggling to convert a string to an integer. For instance,
val someString = " 1.9"
Int.fromString someString
returns:
val it SOME 1 : int option
Furthermore, when I try to extract the value from the option type using:
valOf(Int.fromString someString);
it returns:
val it = 1 : int
I am confused as to why is it still converting the string into this integer even though it is a real number. And how can I convert a string to int and handle the errors if any.
I don't know how the conversion in every implementation works, but in Poly/ML a valid int will be returned if a valid int has been read thus far - even if the whole string is not a valid int.
As molbdnilo pointed out, it will be easier to use the Char.isDigit function (or your own that allows more int cases) to check if the string is an int:
List.all Char.isDigit (String.explode someString)
Concerning your confusion with valOf, this is completely to be expected because you already saw Int.fromString returned an int option. The valOf
function is defined like this:
fun valOf (opt: 'a option) : 'a =
case opt of
NONE => raise Fail "option is NONE"
| SOME a => a
So since you saw that Int.fromString " 1.9"
returned SOME 1
, it must be the case that valOf (Int.fromString " 1.9")
returns 1
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With