Advertisement
banovski

Primitive RPN calculator

Oct 6th, 2022 (edited)
2,232
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Haskell 1.12 KB | Source Code | 0 0
  1. -- A primitive command line reverse polish notation calculator. Valid
  2. -- operations are adding, subtraction, multiplication, division.
  3.  
  4. main :: IO ()
  5. main = do
  6.   putStrLn
  7.     "Enter a valid RPN expression with '+', '-', '*', '/' operators or 'quit'; hit ENTER"
  8.   interaction
  9.  
  10. interaction :: IO ()
  11. interaction = do
  12.   input <- getLine
  13.   if input == "quit"
  14.     then return ()
  15.     else if not $ all (`elem` "0123456789+-*/. ") input
  16.            then do
  17.              putStrLn "Invalid characters detected; try again"
  18.              interaction
  19.            else do
  20.              putStrLn $ head $ fold input
  21.              interaction
  22.  
  23. fold :: String -> [String]
  24. fold s = foldl stackOrCalculate [] $ words s
  25.  
  26. stackOrCalculate :: [String] -> String -> [String]
  27. stackOrCalculate a v =
  28.   if v `notElem` ["+", "-", "*", "/"]
  29.     then v : a
  30.     else calculate a v
  31.  
  32. calculate :: [String] -> String -> [String]
  33. calculate (a1:a2:as) v =
  34.   let aux r = show r : as
  35.       x = read a2
  36.       y = read a1
  37.    in case v of
  38.         "+" -> aux $ x + y
  39.         "-" -> aux $ x - y
  40.         "*" -> aux $ x * y
  41.         "/" -> aux $ x / y
  42.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement