Contents

Lec28-Calculator

Calculator

Exception

/lec28-calculator/image.png

1
raise Exception("Invalid input")
1
2
3
4
try:
    # code that may raise an exception
except Exception as e:
    print(e)

见java try-catch 😏

1
2
float('inf') # positive infinity
float('-inf') # negative infinity

Programming Languages

  • Programs are trees… and the way interpreters work is through a tree recursion.

/lec28-calculator/image-1.png

Parsing

把文本转化为抽象语法树(Abstract Syntax Tree,AST)

base case: only symbols and numbers

recursive case: expressions and statements

Scheme-Syntax Calculator

/lec28-calculator/image-2.png

using Python Pair to describe pairs of expressions and statements

the eval function

/lec28-calculator/image-3.png

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
def calc_apply(op, args):
    """
    args: Iterable
    """
    if op == '+':
        ...
    elif op == '-':
        ...
    elif op == '*':
        ...
    elif op == '/':
        ...
    else:
        raise Exception("Invalid operator")

interactive cli

Read-Eval-Print-Loop (REPL) 😮

/lec28-calculator/image-4.png

raise exception

/lec28-calculator/image-5.png