Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- -- A primitive command line reverse polish notation calculator. Valid
- -- operations are adding, subtraction, multiplication, division.
- main :: IO ()
- main = do
- putStrLn
- "Enter a valid RPN expression with '+', '-', '*', '/' operators or 'quit'; hit ENTER"
- interaction
- interaction :: IO ()
- interaction = do
- input <- getLine
- if input == "quit"
- then return ()
- else if not $ all (`elem` "0123456789+-*/. ") input
- then do
- putStrLn "Invalid characters detected; try again"
- interaction
- else do
- putStrLn $ head $ fold input
- interaction
- fold :: String -> [String]
- fold s = foldl stackOrCalculate [] $ words s
- stackOrCalculate :: [String] -> String -> [String]
- stackOrCalculate a v =
- if v `notElem` ["+", "-", "*", "/"]
- then v : a
- else calculate a v
- calculate :: [String] -> String -> [String]
- calculate (a1:a2:as) v =
- let aux r = show r : as
- x = read a2
- y = read a1
- in case v of
- "+" -> aux $ x + y
- "-" -> aux $ x - y
- "*" -> aux $ x * y
- "/" -> aux $ x / y
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement