diff options
| author | Oskari Timperi <oskari.timperi@iki.fi> | 2015-12-08 22:27:12 +0200 |
|---|---|---|
| committer | Oskari Timperi <oskari.timperi@iki.fi> | 2015-12-08 22:27:12 +0200 |
| commit | 266012d2beb4bfb0e4b342fb697a2472cba7d25d (patch) | |
| tree | e9bb71142b389c6ce75a558f0e7d7abecc7f7acd | |
| parent | d64e5deb5cd7c853bef96b9d80919a176b703b26 (diff) | |
| download | lbasi-266012d2beb4bfb0e4b342fb697a2472cba7d25d.tar.gz lbasi-266012d2beb4bfb0e4b342fb697a2472cba7d25d.zip | |
handle multiplication and division
| -rw-r--r-- | calc1.pas | 34 | ||||
| -rw-r--r-- | tests/calc1.txt | 3 |
2 files changed, 27 insertions, 10 deletions
@@ -6,7 +6,7 @@ uses typinfo, sysutils, character; type - TokenType = (TT_Integer, TT_Plus, TT_Minus, TT_Eof); + TokenType = (TT_Integer, TT_Plus, TT_Minus, TT_Asterisk, TT_Slash, TT_Eof); Token = class TokenType: TokenType; @@ -82,7 +82,6 @@ begin inherited Create(TT_Minus); end; - constructor TokenEof.Create; begin inherited Create(TT_Eof); @@ -142,22 +141,29 @@ begin if IsDigit(CurChar) then begin Result := TokenInteger.Create(GetInteger); - Exit; end else if CurChar = '+' then begin Result := TokenPlus.Create; Inc(CurPos); - Exit; end else if CurChar = '-' then begin Result := TokenMinus.Create; Inc(CurPos); - Exit; - end; - - Error; + end + else if CurChar = '*' then + begin + Result := Token.Create(TT_Asterisk); + Inc(CurPos); + end + else if CurChar = '/' then + begin + Result := Token.Create(TT_Slash); + Inc(CurPos); + end + else + Error; end; procedure Interpreter.Eat(T: TokenType); @@ -183,16 +189,24 @@ begin if Op.TokenType = TT_Plus then Eat(TT_Plus) + else if Op.TokenType = TT_Minus then + Eat(TT_Minus) + else if Op.TokenType = TT_Asterisk then + Eat(TT_Asterisk) else - Eat(TT_Minus); + Eat(TT_Slash); Right := Current; Eat(TT_Integer); if Op.TokenType = TT_Plus then Result := TokenInteger(Left).Val + TokenInteger(Right).Val + else if Op.TokenType = TT_Minus then + Result := TokenInteger(Left).Val - TokenInteger(Right).Val + else if Op.TokenType = TT_Asterisk then + Result := TokenInteger(Left).Val * TokenInteger(Right).Val else - Result := TokenInteger(Left).Val - TokenInteger(Right).Val; + Result := Round(TokenInteger(Left).Val / TokenInteger(Right).Val); end; var diff --git a/tests/calc1.txt b/tests/calc1.txt index ac08e76..ad30e6e 100644 --- a/tests/calc1.txt +++ b/tests/calc1.txt @@ -28,3 +28,6 @@ Simple calculations 1+1 2 100+3 103 34 +${SPACE*4}6 40 + + 10/2 5 + 3*4 12 |
