Add sqrt operator
This commit is contained in:
parent
a22012eb45
commit
d7fe9c4ee5
|
@ -14,6 +14,7 @@ MINUS = 'MINUS'
|
|||
MUL = 'MUL'
|
||||
DIV = 'DIV'
|
||||
POW = 'POW'
|
||||
SQRT = 'SQRT'
|
||||
|
||||
HEX = 'HEX'
|
||||
DEC = 'DEC'
|
||||
|
|
|
@ -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)
|
||||
|
|
11
lexer.py
11
lexer.py
|
@ -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)
|
||||
|
||||
|
|
Loading…
Reference in New Issue