summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorDaniel Silverstone <dsilvers@digital-scurf.org>2013-03-10 16:55:08 +0000
committerDaniel Silverstone <dsilvers@digital-scurf.org>2013-03-10 16:55:08 +0000
commit7065d160aca5f025e51fb8b567d24b08f2bbe558 (patch)
tree56612d45d998ea4ebc5cf383b09031398403ee20
parentdf3595ddb9cebf50072fcf1c0186261c998dad15 (diff)
downloadcalculator-7065d160aca5f025e51fb8b567d24b08f2bbe558.tar.bz2
Added assignment statements
-rw-r--r--calculator.hs26
1 files changed, 21 insertions, 5 deletions
diff --git a/calculator.hs b/calculator.hs
index 2c2b5b7..040c1d3 100644
--- a/calculator.hs
+++ b/calculator.hs
@@ -17,6 +17,7 @@ data Expression = Constant Double
deriving (Show)
data Statement = PrintStatement Expression
+ | AssignmentStatement String Expression
deriving (Show)
lexer :: TokenParser ()
@@ -52,11 +53,19 @@ parsePrint = do
reserved lexer "print"
expr <- parseExpression
return $ PrintStatement expr
+
+parseAssignment :: Parser Statement
+parseAssignment = do
+ reserved lexer "let"
+ ident <- identifier lexer
+ reservedOp lexer "="
+ expr <- parseExpression
+ return $ AssignmentStatement ident expr
parseInput :: Parser Statement
parseInput = do
whiteSpace lexer
- s <- parsePrint
+ s <- (parsePrint <|> parseAssignment)
eof
return s
@@ -103,6 +112,9 @@ interpretStatement :: Statement -> Calculator ()
interpretStatement (PrintStatement expr) = do
n <- interpretExpression expr
liftIO $ print n
+interpretStatement (AssignmentStatement ident expr) = do
+ n <- interpretExpression expr
+ modify (M.insert ident (Constant n))
defaultVars :: M.Map String Expression
defaultVars = M.fromList
@@ -111,13 +123,17 @@ defaultVars = M.fromList
, ("phi", Constant ((1 + (sqrt 5)) / 2))
]
-calculate :: String -> IO ()
+calculate :: String -> Calculator ()
calculate s =
case ret of
- Left e -> putStrLn $ "error: " ++ (show e)
- Right n -> evalStateT (interpretStatement n) defaultVars
+ Left e -> liftIO $ putStrLn $ "error: " ++ (show e)
+ Right n -> interpretStatement n
where
ret = parse parseInput "" s
+calculator :: Calculator ()
+calculator =
+ liftIO getContents >>= (mapM_ calculate) . lines
+
main :: IO ()
-main = getContents >>= (mapM_ calculate) . lines
+main = evalStateT calculator defaultVars