wvogel日記

自分用の技術備忘録が多めです.

四則演算

Haskellで、四則演算を書いてみた

priority :: Char -> Int
priority c
    | c == '+' || c == '-' = 1
    | otherwise = 2

calc :: String -> [Int] -> Int
calc (x:xs) num@(n:ns)
    | ns == [] = n
    | xs == [] = calc' x num
    | priority x >= priority (head xs) = calc (xs)  ((calc' x num):tail ns)
    | otherwise = calc (x:tail xs) (n:(calc' (head xs) ns):drop 2 ns)
        where
        calc' x (n:m:_)
            | x == '+' = n+m
            | x == '-' = n-m
            | x == '*' = n*m

main = do cs <- getLine;
            print $ calc (ope cs) (map read $ words $ numbers cs)

ope :: String -> String
ope (c:cs)
    | cs == [] = []
    | c >= '0' && c <= '9' = ope cs
    | otherwise = c:ope cs

numbers :: String -> String
numbers (c:cs)
    | cs == [] = [c]
    | c >= '0' && c <= '9' = c:numbers cs
    | otherwise = ' ':numbers cs

演算子と数値部分を分けて、演算子の優先順位によって場合分け。
もっとスマートに書けるだろうけど、パッと書いたらこんな感じ。
()
処理はしてないので、それに対応させないと
あ、あと割り算処理足すの忘れてる笑