Skip to content

Instantly share code, notes, and snippets.

@monzou
Created June 30, 2012 07:01
Show Gist options
  • Save monzou/3022732 to your computer and use it in GitHub Desktop.
Save monzou/3022732 to your computer and use it in GitHub Desktop.
逆ポーランド記法電卓
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