Created
June 30, 2012 07:01
-
-
Save monzou/3022732 to your computer and use it in GitHub Desktop.
逆ポーランド記法電卓
This file contains hidden or 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 (fold foldingFunction [] (words expression)) をポインタフリースタイルで書いた ↓ | |
solveRPN = head . foldl foldingFunction [] . words | |
where | |
-- foldingFunction stack operator | |
-- stack は x:y:ys に分割し, x と y を operator で評価してスタックの先頭を置き換える | |
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 xs numberString = read numberString:xs | |
main = print $ solveRPN "10 4 3 + 2 * - 2 ^ 2 /" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment