DOC PREVIEW
Berkeley COMPSCI 61A - Lecture 26

This preview shows page 1-2-3-4 out of 12 pages.

Save
View full document
View full document
Premium Document
Do you want full access? Go Premium and unlock all 12 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 12 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 12 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 12 pages.
Access to all documents
Download any document
Ad free experience
Premium Document
Do you want full access? Go Premium and unlock all 12 pages.
Access to all documents
Download any document
Ad free experience

Unformatted text preview:

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, orthe 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 recursivelyEvaluate each operand expressionCollect their values as a list of argumentsApply 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

Berkeley COMPSCI 61A - Lecture 26

Documents in this Course
Lecture 1

Lecture 1

68 pages

Midterm

Midterm

5 pages

Midterm

Midterm

6 pages

Lecture 35

Lecture 35

250 pages

Lecture 14

Lecture 14

125 pages

Lecture 2

Lecture 2

159 pages

Lecture 6

Lecture 6

113 pages

Lecture 3

Lecture 3

162 pages

Homework

Homework

25 pages

Lecture 13

Lecture 13

117 pages

Lecture 29

Lecture 29

104 pages

Lecture 11

Lecture 11

173 pages

Lecture 7

Lecture 7

104 pages

Midterm

Midterm

6 pages

Midterm

Midterm

6 pages

Lecture 8

Lecture 8

108 pages

Lab 4

Lab 4

4 pages

Lecture 7

Lecture 7

52 pages

Lecture 20

Lecture 20

129 pages

Lecture 15

Lecture 15

132 pages

Lecture 9

Lecture 9

95 pages

Lecture 30

Lecture 30

108 pages

Lecture 17

Lecture 17

106 pages

Load more
Download Lecture 26
Our administrator received your request to download this document. We will send you the file to your email shortly.
Loading Unlocking...
Login

Join to view Lecture 26 and access 3M+ class-specific study document.

or
We will never post anything without your permission.
Don't have an account?
Sign Up

Join to view Lecture 26 2 2 and access 3M+ class-specific study document.

or

By creating an account you agree to our Privacy Policy and Terms Of Use

Already a member?