Calculator
Last updated
Last updated
def calc_eval(exp):
if type(exp) in (int, float): # A number evaluates to itself
return exp
# A call expression evaluates to its argument values combined by an operator
# (调用表达式对其参数值进行评估,由一个运算符组合而成。)
elif isinstance(exp, Pair):
# calc_eval: Recursive call returns a number for each operand
# (递归调用为每个操作数返回一个数字。)
arguments = exp.second.map(calc_eval)
# exp.first: '+', '-', '*', '/'
# arguments: A Scheme list of numbers
return calc_apply(exp.first, arguments)
else:
raise TypeError
def calc_apply(operator, args):
if operator == '+':
return reduce(add, args, 0)
elif operator == '-':
...
elif operator == '*':
...
elif operator == '/':
...
else:
raise TypeErrordef read_print_loop():
"""Run a read-print loop for Scheme expressions."""
while True:
try:
src = buffer_input()
while src.more_on_line:
expression = scheme_read(src)
print(repr(expression))
except (SyntaxError, ValueError) as err: # ValueError: 2.3.4; SyntaxError: 额外的‘)’
print(type(err).__name__ + ':', err)
except (KeyboardInterrupt, EOFError): # <Control>-D, etc. 真正的停止方式
return