load "Real"; open TextIO Char String Real exception Eof exception StackUnderflow exception BadOperator of string fun applyOperator operator (s::f::r) = (case operator of "+" => f + s | "-" => f - s | "*" => f * s | "/" => f / s | _ => raise BadOperator operator)::r | applyOperator operator _ = raise StackUnderflow fun handleToken (token, stack) = case fromString token of NONE => applyOperator token stack | SOME(value) => value::stack fun handleInput inStack = (if not (endOfStream stdIn) then let val outStack = foldl handleToken inStack (tokens isSpace (inputLine stdIn)) in if not (null outStack) then (print (toString (hd outStack)); print "\n") else (); handleInput outStack end else raise Eof) handle BadOperator operator => (print ("Bad operator: \"" ^ operator ^ "\"\n"); handleInput inStack) | StackUnderflow => (print "Stack underflow\n"; handleInput inStack) val _ = handleInput nil handle Eof => ()