Guest User

Untitled

a guest
Aug 18th, 2018
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.44 KB | None | 0 0
  1. haskell: RPN Calculator
  2. [] : 3
  3. [3] : 4
  4. [4,3] : +
  5. [7] : c
  6. [] : 123
  7. [123] : 3
  8. [3,123] : *
  9. [369] :
  10.  
  11. import System.Environment
  12. import System.Directory
  13. import System.IO
  14. import Data.List
  15.  
  16. stack = []
  17.  
  18. add1 :: [Int] -> [Int]
  19. add1 [] = []
  20. add1 [x] = [x]
  21. add1 [x,y] = [(x+y)]
  22. add1 x:(y:xs) = (x+y) : (xs : [])
  23.  
  24. --sub :: [Int] -> [Int]
  25. --sub [] = []
  26. --sub x:(y:xs) = (x-y) : xs
  27.  
  28. --mul :: [Int] -> [Int]
  29. --mul [] = []
  30. --mul x:(y:xs) = (x*y) : xs
  31.  
  32. --div :: [Int] -> [Int]
  33. --div [] = []
  34. --div x:(y:xs) = (x/y) : xs
  35.  
  36. c :: [Int] -> [Int]
  37. c = []
  38.  
  39. push :: [Int] -> a -> [Int]
  40. push [] a = [a]
  41. push (x:xs) a = a : (x:xs)
  42.  
  43. dispatch :: [(String, Int -> IO ())]
  44. dispatch = [ ("+", add)
  45. -- , ("-", sub)
  46. -- , ("*", mul)
  47. -- , ("/", div)
  48. ]
  49.  
  50. xcl = do
  51. print stack
  52. answer <- readLine
  53.  
  54. add1 (x:y:xs) = (x+y) : xs
  55.  
  56. push :: [Int] -> Int -> [Int]
  57.  
  58. xcl :: [Int] -> IO ()
  59. xcl st = do
  60. print st
  61. answer <- getLine
  62. case answer of
  63. "q" -> return ()
  64. "c" -> xcl ([] ::[Int])
  65. "+" -> xcl $ add1 st
  66. x -> xcl $ push st $ read x
  67.  
  68. x -> case (reads x) of
  69. [(num,_)] -> xcl $ push st num
  70. _ -> xcl st
  71.  
  72. xcl stack = do
  73. print stack
  74. answer <- getLine
  75. case lookup answer dispatch of
  76. Just function -> -- we have a function, apply it to the top of the stack
  77. Nothing -> -- if we have a number, parse it and push it onto the stack
  78. -- if not, issue an error
Add Comment
Please, Sign In to add comment