Skip to content

Instantly share code, notes, and snippets.

@AngusP
Last active December 31, 2015 23:19
Show Gist options
  • Save AngusP/8058842 to your computer and use it in GitHub Desktop.
Save AngusP/8058842 to your computer and use it in GitHub Desktop.
Reverse Polish Notation
-- 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