Skip to content

Instantly share code, notes, and snippets.

@FMNSSun
Created November 4, 2015 15:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save FMNSSun/72a1df9d987bc31026c6 to your computer and use it in GitHub Desktop.
Save FMNSSun/72a1df9d987bc31026c6 to your computer and use it in GitHub Desktop.
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