http://ja.wikipedia.org/wiki/Haskell の逆ポーランド記法評価器


-- 逆ポーランド記法評価器
-- calc :: String -> [Float]
calc = foldl f [] . words
where
f (x:y:zs) "+" = y+x:zs
f (x:y:zs) "-" = y-x:zs
f (x:y:zs) "*" = y*x:zs
f (x:y:zs) "/" = y/x:zs
f xs y = read y : xs

分かりやすく変数名を変えてみる。


calc :: String -> [Float]
calc string = foldl fnc [] (words string)
where
-- 演算子のときはスタックから数字を取り出し、演算してスタックに積む
-- stack の状態にパターンマッチ
fnc (num1 : num2 : other) "+" = num2 + num1 : other
fnc (num1 : num2 : other) "-" = num2 - num1 : other
fnc (num1 : num2 : other) "*" = num2 * num1 : other
fnc (num1 : num2 : other) "/" = num2 / num1 : other
-- 数字のときはスタックに積む
fnc stack numberString = read numberString : stack

動かしてみる。


*Main> calc "1 2 + 3 *"
[9.0]
*Main> calc "1"
[1.0]
*Main> calc "1 2"
[2.0,1.0]
*Main> calc "1 2 +"
[3.0]
*Main> calc "1 2 + 3"
[3.0,3.0]
*Main> calc "1 2 + 3 *"
[9.0]