Last active
December 31, 2015 23:19
-
-
Save AngusP/8058842 to your computer and use it in GitHub Desktop.
Reverse Polish Notation
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
-- This is from the Morning Exam | |
rpn :: Expr -> [String] | |
rpn X = ["X"] | |
rpn (Const n) = [show n] | |
rpn (a :+: b) = (rpn a) ++ (rpn b) ++ ["+"] | |
rpn (a :*: b) = (rpn a) ++ (rpn b) ++ ["*"] | |
rpn (Neg a) = (rpn a) ++ ["-"] | |
-- NB: I can't really remember how negation was | |
-- represented, this might not be it... | |
evalrpn :: [String] -> Int -> Int | |
evalrpn rpn x = head $ doe rpn x [] | |
where | |
doe :: [String] -> Int -> [Int] -> [Int] | |
doe [] x hold = hold | |
doe ("X":rs) x hold = doe rs x (x:hold) | |
doe ("*":rs) x (a:b:hold) = doe rs x ((a*b):hold) | |
doe ("+":rs) x (a:b:hold) = doe rs x ((a+b):hold) | |
doe ("-":rs) x (a:hold) = doe rs x ((-a):hold) | |
doe (c:rs) x hold = doe rs x ((read c :: Int):hold) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment