Add sqrt operator

This commit is contained in:
Pavle Portic 2019-04-22 17:34:03 +02:00
parent a22012eb45
commit d7fe9c4ee5
Signed by: TheEdgeOfRage
GPG Key ID: 6758ACE46AA2A849
3 changed files with 21 additions and 7 deletions

View File

@ -14,6 +14,7 @@ MINUS = 'MINUS'
MUL = 'MUL'
DIV = 'DIV'
POW = 'POW'
SQRT = 'SQRT'
HEX = 'HEX'
DEC = 'DEC'

View File

@ -8,7 +8,7 @@
from constants import (
NUMBER, EOF,
PLUS, MINUS, MUL, DIV, POW,
PLUS, MINUS, MUL, DIV, POW, SQRT,
HEX, DEC, BIN,
)
@ -40,7 +40,7 @@ class Interpreter:
return value
def evaluate_operator(self, token):
def evaluate_binary_operator(self, token):
if len(self.stack) < 2:
raise Exception('Needs at least 2 values on the stack')
@ -49,6 +49,14 @@ class Interpreter:
self.stack.append(token.value(left, right))
self.eat(token.type)
def evaluate_unary_operator(self, token):
if len(self.stack) < 1:
raise Exception('Needs at least 1 value on the stack')
value = self.get_from_stack()
self.stack.append(token.value(value))
self.eat(token.type)
def set_mode(self, token):
self.mode = token.type
self.mode_func = token.value
@ -59,7 +67,9 @@ class Interpreter:
while token.type is not EOF:
if token.type in (PLUS, MINUS, MUL, DIV, POW):
self.evaluate_operator(token)
self.evaluate_binary_operator(token)
elif token.type in (SQRT):
self.evaluate_unary_operator(token)
elif token.type == NUMBER:
self.stack.append(token.value)
self.eat(NUMBER)

View File

@ -6,12 +6,13 @@
#
# Distributed under terms of the BSD-3-Clause license.
import math
import operator
from token import Token
from constants import (
NUMBER, EOF,
PLUS, MINUS, MUL, DIV, POW,
PLUS, MINUS, MUL, DIV, POW, SQRT,
HEX, DEC, BIN,
)
@ -83,12 +84,14 @@ class Lexer():
text += self.current_char
self.advance()
if text.lower() == 'hex':
if text.lower() == HEX.lower():
return Token(HEX, hex)
elif text.lower() == 'dec':
elif text.lower() == DEC.lower():
return Token(DEC, float)
elif text.lower() == 'bin':
elif text.lower() == BIN.lower():
return Token(BIN, bin)
elif text.lower() == SQRT.lower():
return Token(SQRT, math.sqrt)
else:
self.error(text)