Last active
August 29, 2015 14:25
-
-
Save taisyo7333/33e600a4bc655456e8a8 to your computer and use it in GitHub Desktop.
Haskell : Reverse Polish Notation
This file contains 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
{- | |
Reverse Polish Notation | |
>example | |
rpn "10 4 3 + 2 * - " | |
-4.0 | |
rpn "30 4 +" | |
34.0 | |
rpn "4 3 + 10 *" | |
70.0 | |
-} | |
import System.IO -- putStrLn | |
import System.Environment -- getArgs | |
import Data.Char -- isDigit | |
main = do | |
args <- getArgs | |
dispatch args | |
dispatch :: [String] -> IO () | |
dispatch [expression] = putStrLn $ show $ rpn expression | |
dispatch _ = help | |
{- | |
Command format is ... | |
-} | |
help :: IO () | |
help = do | |
putStr $ "The number of arguments is one.\n" ++ | |
"argument ::= <expression>\n" ++ | |
"<expression> :: = {0..9| |+|-|*|/|} \n" ++ | |
"*** Example *** \n" ++ | |
"prn \"10 4 3 + 2 * -\" \n" ++ | |
"-4.0" ++ | |
"\n" | |
{- | |
This program's body definition is ... | |
-} | |
rpn :: String -> Double | |
rpn expression = parse [] $ words expression | |
{- *** Description *** | |
The list for the stack should has only one value when input string is empty. | |
-} | |
type Stack = [Double] | |
parse :: Stack -> [String] -> Double | |
parse [num] [] = num -- finished parse | |
parse [] [] = error "[???????] Syntax error!!\n" -- maybe not be happned. | |
parse (num:nums) [] = error "[Operand] Syntax error!!\n" | |
--parse (num:nums) [] = num | |
parse stack (x:xs) = parse (operand x stack) xs | |
-- (L) left side value : older data on stack | |
-- (R) right side value : newer data on stack | |
-- "+-*/" | |
operand :: String -> Stack -> Stack | |
operand "+" (right:left:stack) = ( left + right ) :stack | |
operand "+" _ = error "Operand[+] Syntax Error!!" | |
operand "-" (right:left:stack) = ( left - right ) :stack | |
operand "-" _ = error "Operand[-] Syntax Error!!" | |
operand "*" (right:left:stack) = ( left * right ) :stack | |
operand "*" _ = error "Operand[*] Syntax Error!!" | |
operand "/" (right:left:stack) = ( left / right ) :stack | |
operand "/" _ = error "Operand[/] Syntax Error!!" | |
operand numString stack = read numString : stack |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment