Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- haskell: RPN Calculator
- [] : 3
- [3] : 4
- [4,3] : +
- [7] : c
- [] : 123
- [123] : 3
- [3,123] : *
- [369] :
- import System.Environment
- import System.Directory
- import System.IO
- import Data.List
- stack = []
- add1 :: [Int] -> [Int]
- add1 [] = []
- add1 [x] = [x]
- add1 [x,y] = [(x+y)]
- add1 x:(y:xs) = (x+y) : (xs : [])
- --sub :: [Int] -> [Int]
- --sub [] = []
- --sub x:(y:xs) = (x-y) : xs
- --mul :: [Int] -> [Int]
- --mul [] = []
- --mul x:(y:xs) = (x*y) : xs
- --div :: [Int] -> [Int]
- --div [] = []
- --div x:(y:xs) = (x/y) : xs
- c :: [Int] -> [Int]
- c = []
- push :: [Int] -> a -> [Int]
- push [] a = [a]
- push (x:xs) a = a : (x:xs)
- dispatch :: [(String, Int -> IO ())]
- dispatch = [ ("+", add)
- -- , ("-", sub)
- -- , ("*", mul)
- -- , ("/", div)
- ]
- xcl = do
- print stack
- answer <- readLine
- add1 (x:y:xs) = (x+y) : xs
- push :: [Int] -> Int -> [Int]
- xcl :: [Int] -> IO ()
- xcl st = do
- print st
- answer <- getLine
- case answer of
- "q" -> return ()
- "c" -> xcl ([] ::[Int])
- "+" -> xcl $ add1 st
- x -> xcl $ push st $ read x
- x -> case (reads x) of
- [(num,_)] -> xcl $ push st num
- _ -> xcl st
- xcl stack = do
- print stack
- answer <- getLine
- case lookup answer dispatch of
- Just function -> -- we have a function, apply it to the top of the stack
- Nothing -> -- if we have a number, parse it and push it onto the stack
- -- if not, issue an error
Add Comment
Please, Sign In to add comment