Ir para o conteúdo

Calculadora RPN - Reverse Polish Notation

import System.IO

type Stack = [Integer]
type Operator = Integer -> Integer -> Integer

apply :: Operator -> Stack -> Stack
apply f (x:y:zs) = (f y x) : zs

opList :: [(String, Operator)]
opList = [ ("+", (+)), ("-", (-))
         , ("*", (*)), ("/", div)
         , ("^", (^)) ]

runRPN :: [String] -> Stack -> Integer
runRPN [] (t:_) = t
runRPN (curr:rest) stk =
  case lookup curr opList of
    Just op -> runRPN rest $ apply op stk
    Nothing -> runRPN rest $ (read curr) : stk

main :: IO ()
main = interact $ unlines . map f . lines
  where f x = show $ runRPN (words x) []