Search code examples
smlnj

How to get an integer as user input in SML


I'm trying to get a number from a user. That number is then used to call another function randomList(n) which takes the given number and uses it. I keep getting the error exception option. I've read that adding SOME to the variable declaration or valOf can fix this issue, but it is not working for me. What do I need to change?

fun getNumber() = 
print "Please enter the number of integers: ";
let
    val str = valOf (TextIO.inputLine TextIO.stdIn)
    val i : int = valOf (Int.fromString str)
    in 
    randomList(i)
end;
getNumber();

Solution

  • The issue here is that fun getNumber() only encompasses the print statement on the following line. You need to enclose the print and the let within parenthesis if you want them to both be a part of getNumber().

    For example, the following code compiles and echos the input integer that is passed in via stdin:

    fun getNumber() = (
    print "Please enter the number of integers: ";
    let
        val str = valOf (TextIO.inputLine TextIO.stdIn)
        val i : int = valOf (Int.fromString str)
    in
        print(Int.toString(i))
    end
    );
    getNumber();