61A Lecture 26Monday, October 31Monday, October 31, 2011Programming LanguagesComputers have software written in many different languagesMachine languages: statements can be interpreted by hardware•All data are represented as sequences of bits•All statements are primitive instructionsHigh-level languages: hide concerns about those details•Primitive data types beyond just bits•Statements/expressions can be non-primitive (e.g., calls)•Evaluation process is defined in software, not hardwareHigh-level languages are built on top of low-level languages2Machine languageC PythonMonday, October 31, 2011λf.(λx.f(xx))(λx.f(xx))f(x)=x2− 2x +1Metalinguistic AbstractionMetalinguistic abstraction: Establishing new technical languages (such as programming languages)3In computer science, languages can be implemented:•An interpreter for a programming language is a function that, when applied to an expression of the language, performs the actions required to evaluate that expression•The semantics and syntax of a language must be specified precisely in order to allow for an interpreterMonday, October 31, 2011The Calculator LanguagePrefix notation expression language for basic arithmeticPython-like syntax, with more flexible built-in functions4calc> add(1, 2, 3, 4)10calc> mul()1calc> sub(100, mul(7, add(8, div(-12, -3))))16.0calc> -(100, *(7, +(8, /(-12, -3))))16.0DemoMonday, October 31, 2011Syntax and Semantics of CalculatorExpression types:•A call expression is an operator name followed by a comma-separated list of operand expressions, in parentheses•A primitive expression is a numberOperators:•The {add,+} operator returns the sum of its arguments•The {sub,-} operator returns either the additive inverse of a single argument, orthe sum of subsequent arguments subtracted from the first•The {mul,*} operator returns the product of its arguments•The {div,/} operator returns the real-valued quotient of a dividend and divisor (i.e., a numerator and denominator)5Monday, October 31, 2011Expression TreesA basic interpreter has two parts: a parser and an evaluator6stringparserexpression treeEvaluatorvalue'add(2, 2)' Exp('add', [2, 2]) 4An expression tree is a (hierarchical) data structure that represents a (nested) expression class Exp(object): """A call expression in Calculator.""" def __init__(self, operator, operands): self.operator = operator self.operands = operandsMonday, October 31, 2011Creating Expression Trees DirectlyWe can construct expression trees in Python directlyThe __str__ method of Exp returns a Calculator call expression7>>> Exp('add', [1, 2])Exp('add', [1, 2])>>> str(Exp('add', [1, 2]))'add(1, 2)'>>> Exp('add', [1, Exp('mul', [2, 3, 4])])Exp('add', [1, Exp('mul', [2, 3, 4])])>>> str(Exp('add', [1, Exp('mul', [2, 3, 4])]))'add(1, mul(2, 3, 4))'Monday, October 31, 2011EvaluationEvaluation discovers the form of an expression and then executes a corresponding evaluation rule.•Primitive expressions (literals) are evaluated directly•Call expressions are evaluated recursivelyEvaluate each operand expressionCollect their values as a list of argumentsApply the named operator to the argument list8 def calc_eval(exp): """Evaluate a Calculator expression.""" if type(exp) in (int, float): return exp elif type(exp) == Exp: arguments = list(map(calc_eval, exp.operands)) return calc_apply(exp.operator, arguments)Numbers are self-evaluatingMonday, October 31, 2011Applying OperatorsCalculator has a fixed set of operators that we can enumerate9 def calc_apply(operator, args): """Apply the named operator to a list of args.""" if operator in ('add', '+'): return sum(args) if operator in ('sub', '-'): if len(args) == 1: return -args[0] return sum(args[:1] + [-arg for arg in args[1:]]) ...Dispatch on operator nameImplement operator logic in PythonDemoMonday, October 31, 2011Read-Eval-Print LoopThe user interface to many programming languages is an interactive loop, which•Reads an expression from the user•Parses the input to build an expression tree•Evaluates the expression tree•Prints the resulting value of the expression10 def read_eval_print_loop(): """Run a read-eval-print loop for calculator.""" while True: expression_tree = calc_parse(input('calc> ')) print(calc_eval(expression_tree))Language-specific input promptMonday, October 31, 2011Raising Application ErrorsThe sub and div operators have restrictions on argument numberRaising exceptions in apply can identify such issues11 def calc_apply(operator, args): """Apply the named operator to a list of args.""" ... if operator in ('sub', '-'): if len(args) == 0: raise TypeError(operator + ' requires at least 1 argument') ... ... if operator in ('div', '/'): if len(args) != 2: raise TypeError(operator + ' requires exactly 2 arguments') ...Monday, October 31, 2011Handling ErrorsThe REPL handles errors by printing informative messages for the user, rather than crashing.12A well-designed REPL should not crash on any input! def read_eval_print_loop(): """Run a read-eval-print loop for calculator.""" while True: try: expression_tree = calc_parse(input('calc> ')) print(calc_eval(expression_tree)) except (SyntaxError, TypeError, ZeroDivisionError) as err: print(type(err).__name__ + ':', err) except (KeyboardInterrupt, EOFError): # <Control>-D, etc. print('Calculation completed.') returnDemoMonday, October 31,
View Full Document