fork download
  1. import System.IO
  2.  
  3. type Stack = [Integer]
  4. type Operator = Integer -> Integer -> Integer
  5.  
  6. apply :: Operator -> Stack -> Stack
  7. apply f (x:y:zs) = (f y x) : zs
  8.  
  9. opList :: [(String, Operator)]
  10. opList = [ ("+", (+)), ("-", (-))
  11. , ("*", (*)), ("/", div)
  12. , ("^", (^)) ]
  13.  
  14. runRPN :: [String] -> Stack -> Integer
  15. runRPN [] (t:_) = t
  16. runRPN (curr:rest) stk =
  17. case lookup curr opList of
  18. Just op -> runRPN rest $ apply op stk
  19. Nothing -> runRPN rest $ (read curr) : stk
  20.  
  21. main :: IO ()
  22. main = interact $ unlines . map f . lines
  23. where f x = show $ runRPN (words x) []
Success #stdin #stdout 0s 6304KB
stdin
5 1 2 + 4 * + 3 -
stdout
14