Last active
December 20, 2015 14:58
-
-
Save taiki45/6150397 to your computer and use it in GitHub Desktop.
Haskell 練習: 逆ポーランド記法電卓の実装 一桁の数字のみ…
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
import Data.Char | |
type Stack = [Int] | |
type Machine = (String, Stack) | |
solve :: String -> Int | |
solve exprs = pick $ readExprs $ initMachine exprs where | |
pick (_, [num]) = num | |
initMachine = flip (,) [] | |
isOperand :: Char -> Bool | |
isOperand '+' = True | |
isOperand '-' = True | |
isOperand '*' = True | |
isOperand _ = False | |
toOperand :: Num a => Char -> (a -> a -> a) | |
toOperand '+' = (+) | |
toOperand '-' = (-) | |
toOperand '*' = (*) | |
idElemFor :: Char -> Int | |
idElemFor '+' = 0 | |
idElemFor '-' = 0 | |
idElemFor '*' = 1 | |
readOne :: Machine -> Machine | |
readOne (c:cs, stack) | |
| isOperand c = (cs, [foldr (toOperand c) (idElemFor c) stack]) | |
| isDigit c = (cs, (read [c] :: Int):stack) | |
| isSpace c = (cs, stack) | |
readExprs :: Machine -> Machine | |
readExprs ([], stack) = ([], stack) | |
readExprs machine = readExprs $ readOne machine |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment