Ferramentas de Usuário

Ferramentas de Site


dev_geral:haskell:snippet:rpn

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) []

Discussão no fórum

dev_geral/haskell/snippet/rpn.txt · Última modificação em: 2018/05/14 21:37 (edição externa)