Last active
December 19, 2015 17:18
-
-
Save guipn/5989678 to your computer and use it in GitHub Desktop.
Simple RPN calculator in Haskell.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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