Created
June 10, 2015 12:02
-
-
Save shigemk2/a2d6da8fffae11bf6d9b to your computer and use it in GitHub Desktop.
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
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 (x:y:ys) "^" = (y ** x):ys | |
foldingFunction (x:xs) "ln" = log x:xs | |
foldingFunction xs "sum" = [sum xs] | |
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 + * - +" | |
print $ solveRPN "3 3 4 - +" | |
print $ solveRPN "10 10 10 10 sum 4 /" | |
print $ solveRPN "10 10 10 10 10 sum 4 /" | |
print $ solveRPN "10 4 ^" | |
print $ solveRPN "10000 2 ln" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment