open TextIO; (* loads the structure TextIO in which I/O functions such openIn, inputN, and endOfStream are defined *) exception BadChar; val END = ~1; fun white(c) = c=" " orelse c="\n" orelse c="\t"; fun digit(c) = c >= "0" andalso c <= "9"; fun startInt(file) = (* get the first digit from file; return END if there is no integer *) if endOfStream(file) then END else let val c = inputN(file,1) in if digit(c) then ord(String.sub(c,0))-ord(#"0") else if white(c) then startInt(file) else raise BadChar end; fun finishInt(i,file) = (* return the integer whose first digits have value i and whose remaining digits are found on file, up to the end of the first while space *) if endOfStream(file) then i else let val c = inputN(file,1) in if digit(c) then finishInt(10*i+ord(String.sub(c,0))-ord(#"0"), file) else if white(c) then i else raise BadChar end; fun getInt(file) = (* read an integer from file *) finishInt(startInt(file),file); fun sumInts1(file) = (* sum the integers on file *) let val i = getInt(file) in if i=END then 0 else i+sumInts1(file) end; fun sumInts(filename) = (* sum the integers on file "filename" relative to the current UNIX directory *) sumInts1(openIn(filename));