Created
March 12, 2019 00:34
-
-
Save j-walk/0fe0ceead39ae72624813476711a5850 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Prelude hiding (lex) | |
import Data.Char | |
import Data.Foldable (sequenceA_) | |
import Control.Monad.State | |
data Token = Num Integer | |
| Op Char deriving (Show, Eq) | |
lex :: String -> [Token] | |
lex [] = [] | |
lex str@(s:ss) | isDigit s = (Num . read . takeWhile isDigit $ str) : (lex $ dropWhile isDigit str) | |
| isSpace s = lex $ dropWhile isSpace str | |
| otherwise = Op s : lex ss | |
toOp :: Token -> StateT [Integer] IO () | |
toOp t@(Num a) = do | |
st <- get | |
put (a:st) | |
toOp (Op o) = do | |
st <- get | |
case o of | |
'+' -> put $ (st !! 0 + st !! 1) : (drop 2 st) | |
'p' -> lift $ putStrLn $ show $ head st | |
-- fill in the rest of ops e.g. -/*^ etc | |
rpnCalc :: String -> IO () | |
rpnCalc str = evalStateT (sequenceA_ . map toOp . lex $ str) [] | |
main = rpnCalc "1 2 + p" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment