Mon, 04 May 2015 03:11:14 +0300
Use a value class
calc.py | file | annotate | diff | comparison | revisions |
--- a/calc.py Mon May 04 02:46:09 2015 +0300 +++ b/calc.py Mon May 04 03:11:14 2015 +0300 @@ -76,6 +76,16 @@ def __repr__ (self): return self.__str__() +class Value (object): + def __init__ (self, value, base): + self.value = value + + def __str__ (self): + return '''<value %s>''' % (self.value) + + def __repr__ (self): + return self.__str__() + def do_realf (func, *args): for x in args: if x.imag: @@ -338,7 +348,7 @@ raise ValueError ('end of expression encountered while parsing ' 'base-%d literal' % base) - return (complex (int (expr[startingIndex:i], base), 0), i) + return (Value (int (expr[startingIndex:i], base)), i) if expr[0] == 'i': # Special case, we just have 'i' -- need special handling here because otherwise this would @@ -351,9 +361,9 @@ try: while i < len (expr): if expr[i] == 'i': - value = complex (0.0, float (expr[:i])) + value = Value (float (expr[:i]) * 1j) else: - value = complex (float (expr [:i + 1]), 0.0) + value = Value (float (expr [:i + 1])) i += 1 return (value, i) @@ -537,7 +547,7 @@ self.tabs = self.tabs[:-1] printFunc (self.tabs + 'Evaluating function call: %s' % (sym)) - expr[i] = Functions[sym.funcname]['function'] (*sym.args) + expr[i] = Value (Functions[sym.funcname]['function'] (*[x.value for x in sym.args])) printFunc (self.tabs + '-> %s' % expr[i]) i += 1 @@ -561,7 +571,7 @@ args = [expr[x] for x in argIndices] argIndices = sorted (argIndices, reverse=True) printFunc (self.tabs + 'Processing: (%s, %d) with args %s' % (op, i, args)) - expr[i] = op.function (*args) + expr[i] = Value (op.function (*[x.value for x in args])) printFunc (self.tabs + '-> %s' % expr[i]) for i2 in argIndices: @@ -653,5 +663,5 @@ self.process_parens (expr) self.process_functions (expr) self.process_operators (expr) - result = self.evaluate (expr, verbose) + result = self.evaluate (expr, verbose).value return self.represent (result)