Created
November 9, 2014 18:47
-
-
Save LukaHorvat/aeaafc4bd2a977b1f6b2 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
--A simple stack-based RPN interpreter | |
rpnCalc :: String -> Int | |
rpnCalc expr = if null res then 0 else head res where | |
res = foldl eval [] expr | |
eval stack c | |
| c `elem` ['0'..'9'] = digitToInt c : stack | |
| otherwise = func c top2 top1 : pop2 | |
where (top1, _) = pop 1 stack | |
(top2, pop2) = pop 2 stack | |
--Char to function mappings | |
func '+' = (+) | |
func '-' = (-) | |
func '*' = (*) | |
func '/' = div | |
func '^' = (^) | |
func _ = error "Invalid RPN expression" | |
--Expression validation | |
pop n l | lengthGEQ n l = let (x, xs) = splitAt n l in (last x, xs) | |
| otherwise = error "Invalid RPN expression" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment