functional-programmingsmlsmlnjml

SML: Exception while reading a line of integers


fun parse file =
 let
(* A function to read an integer from specified input. *)
     fun readInt input =
   Option.valOf (TextIO.scanStream (Int.scan StringCvt.DEC) input)


 
          in
              (Array.update(acc,readInt inStream, f+1); readInts (i - 1) sumd acc has)
          end
 in
      (a, b, readInts b 0 empty [])
 end
(* ................................................................*)

I want to read from a text file that will contain 2 lines:
the first will contain 2 integers a, b
the second will contain b integers x1, x2,.. xb.
for example it will be in this form :

    a b 
    n1 n2 n3 .. nb

I get this error message :

uncaught exception Option
  raised at: Basis/Implementation/option.sml:19.25-19.31  

Line 19: is basically readInts i sumd acc has if that helps.
The problem with my code is because of readInts function. I want to read integer by integer, and not the whole line at once (so I can not use functions like "explode") (it's not like I am forced to do it that way, but it's move time productive to read once and form my desired array acc and list has, instead of reading and storing the b integers in a buffer list and then re-run the list to form my wanted data). Can you see what's the problem with my code?


Solution

  • You call readInt twice in the second case of readInts, advancing the stream past two numbers instead of just one. As you have b numbers in your input, but do this b times, you attempt to read 2 * b numbers and eventually can't anymore. When this happens TextIO.scanStream (Int.scan StringCvt.DEC) input is NONE, so Option.valOf raises Option.