Skip to content

Instantly share code, notes, and snippets.

@guipn
Last active December 19, 2015 17:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save guipn/5989678 to your computer and use it in GitHub Desktop.
Save guipn/5989678 to your computer and use it in GitHub Desktop.
Simple RPN calculator in Haskell.
module Main where
import System.Environment(getArgs)
type Value = Double
type Operand = Value
type Result = Value
type BinaryOp = Operand -> Operand -> Result
type Arguments = [String]
type Stack = [Value]
type Name = String
main :: IO ()
main = do
args <- getArgs
putStrLn $ show $ process args []
functions :: [(Name, BinaryOp)];
functions = [("+", (+)), ("-", (-)), ("*", (*)), ("/", (/))]
process :: Arguments -> Stack -> Double
process [] stack = head stack
process input stack = case lookup symbol functions of
Nothing -> plugNext readOperand
Just op -> plugNext $ binaryAppl op
where symbol = head input
plugNext = process (tail input)
binaryAppl f = (f (head stack) (stack !! 1)) : (drop 2 stack)
readOperand = (read $ head input) : stack
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment