Skip to content

Instantly share code, notes, and snippets.

@FMNSSun
Created Nov 4, 2015
Embed
What would you like to do?
Interpreter for simple postfix expressions
import Data.List
import Data.Char
import System.Environment
isOp :: String -> Bool
isOp x = x `isInfixOf` "+-*/"
isInt :: String -> Bool
isInt ('-':x:xs) = isInt (x:xs)
isInt x = all isDigit $ x
eval' :: [(String,String)] -> [Int] -> [Int]
eval' [("", _)] st = st
eval' [(x, xs)] st
|isInt x = eval' (lex xs) $ ((read x) :: Int) : st
|isOp x = case st of
(b : a : ss) -> eval' (lex xs) ((doOp x a b) : ss)
_ -> error "Stack too small!"
|otherwise = error "Unknown token :("
where doOp "+" a b = a + b
doOp "-" a b = a - b
doOp "*" a b = a * b
doOp "/" a b = a `div` b
doOp _ _ _ = error "Unknown operation!"
eval' [] st = st
eval :: String -> [Int]
eval str = eval' (lex str) []
main :: IO ()
main = do
args <- getArgs
case args of
[exp] -> print . eval $ exp
_ -> do
pn <- getProgName
putStrLn $ "Usage: " ++ pn ++ " <expr>"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment