61A Lecture 26. Monday, October 31

Similar documents
INTERPRETATION AND SCHEME LISTS 12

INTERPRETATION AND SCHEME LISTS 12

Public-Service Announcement

INTERPRETERS AND TAIL CALLS 9

EXCEPTIONS, CALCULATOR 10

INTERPRETERS 8. 1 Calculator COMPUTER SCIENCE 61A. November 3, 2016

Interpreters and Tail Calls Fall 2017 Discussion 8: November 1, 2017 Solutions. 1 Calculator. calc> (+ 2 2) 4

CALCULATOR Calculator COMPUTER SCIENCE 61A. July 24, 2014

Parsing CSCI-400. Principles of Programming Languages.

SCHEME AND CALCULATOR 5b

SCHEME INTERPRETER GUIDE 4

Jim Lambers ENERGY 211 / CME 211 Autumn Quarter Programming Project 4

Ruby: Introduction, Basics

Review 3. Exceptions and Try-Except Blocks

Ruby: Introduction, Basics

Fundamentals of Programming (Python) Getting Started with Programming

Getting Started with Python

CS 360 Programming Languages Interpreters

DEBUGGING TIPS. 1 Introduction COMPUTER SCIENCE 61A

Lecture 2: Big-Step Semantics

Ruby: Introduction, Basics

ENGR 101 Engineering Design Workshop

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression

Creating a new data type

CSE P 501 Exam 8/5/04

6.184 Lecture 4. Interpretation. Tweaked by Ben Vandiver Compiled by Mike Phillips Original material by Eric Grimson

CSE 115. Introduction to Computer Science I

A simple syntax-directed

61A Lecture 2. Friday, August 28, 2015

Exceptions CS GMU

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines.

COMP519 Web Programming Lecture 20: Python (Part 4) Handouts

Here n is a variable name. The value of that variable is 176.

STRUCTURE AND INTERPRETATION COMPUTER PROGRAMS >>> COMPUTER SCIENCE IN THE NEWS. CS61A Lecture 23 Py TODAY REVIEW: INTERPRETATION 7/26/2012 READ PRINT

STRUCTURE AND INTERPRETATION COMPUTER PROGRAMS COMPUTER SCIENCE IN THE NEWS. CS61A Lecture 23 Py TODAY 7/26/2012

What is an Exception? Exception Handling. What is an Exception? What is an Exception? test = [1,2,3] test[3]

Outline. the try-except statement the try-finally statement. exceptions are classes raising exceptions defining exceptions

There are four numeric types: 1. Integers, represented as a 32 bit (or longer) quantity. Digits sequences (possibly) signed are integer literals:

! The simplest building blocks of a language. ! Compound elements are built from simpler ones

On a 64-bit CPU. Size/Range vary by CPU model and Word size.

Why do we need an interpreter? SICP Interpretation part 1. Role of each part of the interpreter. 1. Arithmetic calculator.

Operators and Expressions

Python Essential Reference, Second Edition - Chapter 5: Control Flow Page 1 of 8

Advanced Algorithms and Computational Models (module A)

CS251 Programming Languages Handout # 29 Prof. Lyn Turbak March 7, 2007 Wellesley College

Adding Binary Integers. Part 5. Adding Base 10 Numbers. Adding 2's Complement. Adding Binary Example = 10. Arithmetic Logic Unit

Computational Mathematics with Python

Python for C programmers

CS61A Lecture 23 Py. Jom Magrotker UC Berkeley EECS July 26, 2012

Principles of Programming Languages 2017W, Functional Programming

Lecture 18. Classes and Types

Syntax and Grammars 1 / 21

Absent: Lecture 3 Page 1. def foo(a, b): a = 5 b[0] = 99

Lecture 12: Conditional Expressions and Local Binding

A Simple Syntax-Directed Translator

61A Lecture 25. Friday, October 28

Chapter 4 Section 2 Operations on Decimals

Lecture 2: Python Arithmetic

VENTURE. Section 1. Lexical Elements. 1.1 Identifiers. 1.2 Keywords. 1.3 Literals


Lecture 21. Programming with Subclasses

Getting Started Values, Expressions, and Statements CS GMU

Bindings & Substitution

PREPARING FOR PRELIM 1

afewadminnotes CSC324 Formal Language Theory Dealing with Ambiguity: Precedence Example Office Hours: (in BA 4237) Monday 3 4pm Wednesdays 1 2pm

Introduction to lambda calculus Part 3

61A Lecture 2. Wednesday, September 4, 2013

LECTURE 3. Compiler Phases

PRG PROGRAMMING ESSENTIALS. Lecture 2 Program flow, Conditionals, Loops

CS61A Lecture 32. Amir Kamil UC Berkeley April 5, 2013

Python File Modes. Mode Description. Open a file for reading. (default)

6.001 Notes: Section 15.1

Computer Science 21b: Structure and Interpretation of Computer Programs (Spring Term, 2004)

CIT 590 Homework 6 Fractions

Basic Concepts. Computer Science. Programming history Algorithms Pseudo code. Computer - Science Andrew Case 2

CS1 Lecture 3 Jan. 18, 2019

Full file at

Class extension and. Exception handling. Genome 559

Streams, Delayed Evaluation and a Normal Order Interpreter. CS 550 Programming Languages Jeremy Johnson

Chapter 9: Dealing with Errors

More Things We Can Do With It! Overview. Circle Calculations. πr 2. π = More operators and expression types More statements

COMP-421 Compiler Design. Presented by Dr Ioanna Dionysiou

Fundamentals: Expressions and Assignment

CS301 Compiler Design and Implementation Handout # 18 Prof. Lyn Turbak February 19, 2003 Wellesley College

Test I Solutions MASSACHUSETTS INSTITUTE OF TECHNOLOGY Spring Department of Electrical Engineering and Computer Science

TAIL RECURSION, SCOPE, AND PROJECT 4 11

flex is not a bad tool to use for doing modest text transformations and for programs that collect statistics on input.

Lecture 21. Programming with Subclasses

CS 115 Lecture 4. More Python; testing software. Neil Moore

Assignment 7: functions and closure conversion (part 1)

CHAD Language Reference Manual

Module 2 - Part 2 DATA TYPES AND EXPRESSIONS 1/15/19 CSE 1321 MODULE 2 1

Static Semantics. Lecture 15. (Notes by P. N. Hilfinger and R. Bodik) 2/29/08 Prof. Hilfinger, CS164 Lecture 15 1

Getting Started. Office Hours. CSE 231, Rich Enbody. After class By appointment send an . Michigan State University CSE 231, Fall 2013

Scheme: Strings Scheme: I/O

Lecture 3 Tao Wang 1

CS61A Notes Week 13: Interpreters

CSE : Python Programming. Homework 5 and Projects. Announcements. Course project: Overview. Course Project: Grading criteria

CSE 341 Section 7. Ethan Shea Autumn Adapted from slides by Nicholas Shahan, Dan Grossman, Tam Dang, and Eric Mullen

CS1622. Semantic Analysis. The Compiler So Far. Lecture 15 Semantic Analysis. How to build symbol tables How to use them to find

Transcription:

61A Lecture 26 Monday, October 31

Programming Languages Computers have software written in many different languages Machine languages: statements can be interpreted by hardware All data are represented as sequences of bits All statements are primitive instructions High-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 hardware High-level languages are built on top of low-level languages Machine language C Python 2

Metalinguistic Abstraction Metalinguistic abstraction: Establishing new technical languages (such as programming languages) f(x) =x 2 2x +1 λf.(λx.f(x x))(λx.f(x x)) In 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 interpreter 3

The Calculator Language Prefix notation expression language for basic arithmetic Python-like syntax, with more flexible built-in functions calc> add(1, 2, 3, 4) 10 calc> mul() 1 calc> sub(100, mul(7, add(8, div(-12, -3)))) 16.0 calc> -(100, *(7, +(8, /(-12, -3)))) 16.0 Demo 4

Syntax and Semantics of Calculator Expression types: A call expression is an operator name followed by a commaseparated list of operand expressions, in parentheses A primitive expression is a number Operators: 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) 5

Expression Trees A basic interpreter has two parts: a parser and an evaluator string parser expression tree Evaluator value 'add(2, 2)' Exp('add', [2, 2]) 4 An 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 = operands 6

Creating Expression Trees Directly We can construct expression trees in Python directly The str method of Exp returns a Calculator call expression >>> 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))' 7

Evaluation Evaluation 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 list def calc_eval(exp): """Evaluate a Calculator expression.""" if type(exp) in (int, float): return exp elif type(exp) == Exp: Numbers are self-evaluating arguments = list(map(calc_eval, exp.operands)) return calc_apply(exp.operator, arguments) 8

Applying Operators Calculator has a fixed set of operators that we can enumerate def calc_apply(operator, args): """Apply the named operator to a list of args.""" if operator in ('add', '+'): return sum(args) Dispatch on operator name if operator in ('sub', '-'): if len(args) == 1: return -args[0] Implement operator logic in Python return sum(args[:1] + [-arg for arg in args[1:]])... Demo 9

Read-Eval-Print Loop The 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 expression 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 prompt 10

Raising Application Errors The sub and div operators have restrictions on argument number Raising exceptions in apply can identify such issues 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')... 11

Handling Errors The REPL handles errors by printing informative messages for the user, rather than crashing. 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.') return A well-designed REPL should not crash on any input! Demo 12