4

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.

2
  • This doc might help you sml.sourceforge.net/Basis/option.html Commented Mar 7, 2016 at 5:12
  • fromString succeds if the string begins with an integer. You probably want to write your own converter that checks if every character in the string is a digit. Commented Mar 7, 2016 at 9:47

1 Answer 1

7

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.