Skip to content

Instantly share code, notes, and snippets.

@taiki45
Last active December 20, 2015 14:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save taiki45/6150397 to your computer and use it in GitHub Desktop.
Save taiki45/6150397 to your computer and use it in GitHub Desktop.
Haskell 練習: 逆ポーランド記法電卓の実装 一桁の数字のみ…
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