Solving expression in Reverse Polish Notation using Haskell pattern match:

1
2
3
4
5
6
7
8
9
10
solveRPN :: (Read a, Num a) => String -> a
solveRPN line = head $ foldl push [] $ words line
where
push (y:x:res) "*" = (x*y) : res
push (y:x:res) "+" = (x+y) : res
push (y:x:res) "-" = (x-y) : res
push res n = read n : res

main = do
print $ solveRPN "10 4 3 + 2 * -" -- => -4