Skip to content

Instantly share code, notes, and snippets.

@LukaHorvat
Created November 9, 2014 18:47
Show Gist options
  • Save LukaHorvat/aeaafc4bd2a977b1f6b2 to your computer and use it in GitHub Desktop.
Save LukaHorvat/aeaafc4bd2a977b1f6b2 to your computer and use it in GitHub Desktop.
--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