Skip to content

Instantly share code, notes, and snippets.

@shigemk2
Created June 10, 2015 11:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shigemk2/5c5509e4a9cd3fc552c2 to your computer and use it in GitHub Desktop.
Save shigemk2/5c5509e4a9cd3fc552c2 to your computer and use it in GitHub Desktop.
solveRPN :: String -> Double
-- solveRPN expression = head (foldl foldingFunction [] (words expression))
solveRPN = head . foldl foldingFunction [] . words
-- where foldingFunction stack item = ...
where foldingFunction (x:y:ys) "*" = (y * x):ys
foldingFunction (x:y:ys) "+" = (y + x):ys
foldingFunction (x:y:ys) "-" = (y - x):ys
foldingFunction (x:y:ys) "/" = (y / x):ys
foldingFunction xs numberString = read numberString:xs
main = do
print $ solveRPN "3 2 +"
print $ solveRPN "3 3.5 +"
print $ solveRPN "10 4 3 + 2 * -"
print $ solveRPN "90 34 12 33 55 66 + * - +"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment