Question

I'm trying to make a program in SML that will read in a series/list/sequence of numbers from the user, process the numbers, and output the result. I don't know how many numbers the user will input. The program can either read in all the numbers and output the results all together or read and output one at a time. I don't care whether the input is in a separate file or manually input at a console.

What do I need to do to be able to read input?

fun fact x = if x<2 then 1 else x*fact(x-1); 

let val keepgoing:bool ref = ref true in
   while !keepgoing do
      let val num = valOf(TextIO.inputLine TextIO.stdIn) in 
      print( Int.toString( fact( valOf( Int.fromString( num ) ) ) ) );
      keepgoing := (null(explode(num)))
   end
end;

Sorry about the convoluted conversions. If you also know an easier way to read in integers, I'd appreciate that, too.

Was it helpful?

Solution

Your logic is just flawed here. You want keepgoing := not (null (explode num)). Right? It works fine for me with that change. You need to implement removal of the final newline (so null explode does what you want) and parsing a line with more than one number, but you basically have the right idea.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top