RLISTS AND THE ENVIRONMENT MODEL 9

Similar documents
MEMOIZATION, RECURSIVE DATA, AND SETS

ENVIRONMENT MODEL: FUNCTIONS, DATA 18

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

SCHEME AND CALCULATOR 5b

61A Lecture 2. Wednesday, September 4, 2013

LINKED LISTS AND MIDTERM REVIEW 6

61A Lecture 2. Friday, August 28, 2015

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

61A LECTURE 15 MEMOIZATION, RECURSIVE DATA, SETS

Summer 2017 Discussion 10: July 25, Introduction. 2 Primitives and Define

MUTABLE LISTS AND DICTIONARIES 4

Structure and Interpretation of Computer Programs Spring 2014 Test 2

SCHEME 8. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. March 23, 2017

INTERPRETERS AND TAIL CALLS 9

TAIL RECURSION, SCOPE, AND PROJECT 4 11

Iterators & Generators

Structure and Interpretation of Computer Programs Spring 2014 Final (with corrections)

Structure and Interpretation of Computer Programs Summer 2015 Midterm 2

TUPLES AND RECURSIVE LISTS 5

Structure and Interpretation of Computer Programs Fall 2012 Alternate Midterm 1

INTERPRETATION AND SCHEME LISTS 12

LINKED LISTS AND MIDTERM REVIEW

SCHEME 10 COMPUTER SCIENCE 61A. July 26, Warm Up: Conditional Expressions. 1. What does Scheme print? scm> (if (or #t (/ 1 0)) 1 (/ 1 0))

About the Final. Saturday, 7-10pm in Science Center 101. Closed book, closed notes. Not on the final: graphics, file I/O, vim, unix

SCHEME 7. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. October 29, 2015

Structure and Interpretation of Computer Programs

Structure and Interpretation of Computer Programs

Structure and Interpretation of Computer Programs

Spring 2018 Discussion 7: March 21, Introduction. 2 Primitives

ENVIRONMENT DIAGRAMS AND RECURSION 2

INTERPRETATION AND SCHEME LISTS 12

Fall 2017 Discussion 7: October 25, 2017 Solutions. 1 Introduction. 2 Primitives

EXCEPTIONS, CALCULATOR 10

Structure and Interpretation of Computer Programs

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 of Computer Programs

SCHEME The Scheme Interpreter. 2 Primitives COMPUTER SCIENCE 61A. October 29th, 2012

CS61A Lecture 18. Amir Kamil UC Berkeley March 4, 2013

Lecture #15: Generic Functions and Expressivity. Last modified: Wed Mar 1 15:51: CS61A: Lecture #16 1

Structure and Interpretation of Computer Programs Spring 2019 Midterm 2

Lecture 27: Streams and Lazy Evaluation

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

Structure and Interpretation of Computer Programs

Exercises on ML. Programming Languages. Chanseok Oh

61A LECTURE 17 ORDERS OF GROWTH, EXCEPTIONS. Steven Tang and Eric Tzeng July 23, 2013

A First Look at ML. Chapter Five Modern Programming Languages, 2nd ed. 1

Lecture #12: Mutable Data. map rlist Illustrated (III) map rlist Illustrated. Using Mutability For Construction: map rlist Revisited

Control and Environments Fall 2017 Discussion 1: August 30, Control. If statements. Boolean Operators

CONTROL AND ENVIRONMENTS 1

Quick announcement. Midterm date is Wednesday Oct 24, 11-12pm.

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

Fall 2018 Discussion 8: October 24, 2018 Solutions. 1 Introduction. 2 Primitives

Module 8: Local and functional abstraction

Assignment 7: functions and closure conversion (part 1)

Interpreter Implementation

CS 61A Orders of Growth & Linked Lists Spring 2018 Discussion 6: March 7, Warmup

Lecture #10: Sequences. Last modified: Mon Feb 22 16:33: CS61A: Lecture #10 1

CS61A Lecture 9 Immutable Data Structures. Jom Magrotker UC Berkeley EECS July 2, 2012

61A Lecture 4. Monday, September 9

Computer Science 21b (Spring Term, 2015) Structure and Interpretation of Computer Programs. Lexical addressing

Lecture #12: Mutable Data. Last modified: Sun Feb 19 17:15: CS61A: Lecture #12 1

Environment Diagrams. Administrivia. Agenda Step by Step Environment Diagram Stuff. The Rules. Practice it s on! What are The Rules?

Lecture #12: Immutable and Mutable Data. Last modified: Mon Feb 22 16:33: CS61A: Lecture #12 1

Lists, loops and decisions

Scheme in Scheme: The Metacircular Evaluator Eval and Apply

Control and Environments Fall 2017 Discussion 1: August 30, 2017 Solutions. 1 Control. If statements. Boolean Operators

CS61A Discussion Notes: Week 11: The Metacircular Evaluator By Greg Krimer, with slight modifications by Phoebus Chen (using notes from Todd Segal)

Chapter 3 Programs and Data

Structure and Interpretation of Computer Programs

CS61A Notes Week 13: Interpreters

Introduction to Concepts in Functional Programming. CS16: Introduction to Data Structures & Algorithms Spring 2017

And Parallelism. Parallelism in Prolog. OR Parallelism

Structure and Interpretation of Computer Programs

Objects CHAPTER 6. FIGURE 1. Concrete syntax for the P 3 subset of Python. (In addition to that of P 2.)

Implementing Recursion

Fundamentals of Programming (Python) Object-Oriented Programming. Ali Taheri Sharif University of Technology Spring 2018

MORE SCHEME. 1 What Would Scheme Print? COMPUTER SCIENCE MENTORS 61A. October 30 to November 3, Solution: Solutions begin on the following page.

TREES AND MUTATION 5

Lecture #3: Environments

COMPUTER SCIENCE IN THE NEWS. CS61A Lecture 21 Scheme TODAY REVIEW: DISPATCH DICTIONARIES DISPATCH DICTIONARIES 7/27/2012

Positional, keyword and default arguments

RACKET BASICS, ORDER OF EVALUATION, RECURSION 1

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

ITERATORS AND GENERATORS 10

Module 04: Lists. Topics: Lists and their methods Mutating lists Abstract list functions Readings: ThinkP 8, 10. CS116 Fall : Lists

Structure and Interpretation of Computer Programs

CSC324 Functional Programming Typing, Exceptions in ML

CSCC24 Functional Programming Scheme Part 2

TREES AND ORDERS OF GROWTH 7

DRAWING ENVIRONMENT DIAGRAMS

Intro. Scheme Basics. scm> 5 5. scm>

61A LECTURE 16 TREES, ORDERS OF GROWTH. Steven Tang and Eric Tzeng July 22, 2013

EXPRESSIONS, STATEMENTS, AND FUNCTIONS 1

Lecture #16: Generic Functions and Expressivity. Last modified: Fri Feb 26 19:16: CS61A: Lecture #16 1

Structure and Interpretation of Computer Programs Summer 2014 Midterm 1

CSC324- TUTORIAL 5. Shems Saleh* *Some slides inspired by/based on Afsaneh Fazly s slides

Hacettepe University Computer Engineering Department. Programming in. BBM103 Introduction to Programming Lab 1 Week 4. Fall 2018

CS 234 Python Review Part 2

Overloading. F21SC Industrial Programming: Python: Advanced Language Features. Overloading. Overloading arithmetic operations

Lists How lists are like strings

Transcription:

RLISTS AND THE ENVIRONMENT MODEL 9 COMPUTER SCIENCE 61A July 17, 2012 1 Recursive Lists (RLists) Earlier in the course, we worked with the Immutable Recursive List (IRList), which is an abstract data type consisting of a first (some value) and a rest (another IRList). The end of an IRList was represented by the empty irlist: >>> from irlist import * >>> c_lst = make_irlist( 61a, make_irlist( 61b, make_irlist( 61c, empty_irlist))) >>> irlist_str(c_lst) < 61a, 61b, 61c > For instance, the box-and-pointer diagram of courses would be: This week, we will work with Mutable Recursive Lists (RLists) that are conceptually exactly the same as an IRList. An RList has a first and a rest, but unlike an IRList, you can modify the first and rest of an RList. Here is a shortened class definition of the RList class 1 : class RList(object): 1 The actual class definition of RList is found at: http://inst.eecs.berkeley.edu/ cs61a/su12/lib/rlist.py 1

DISCUSSION 9: RLISTS AND THE ENVIRONMENT MODEL Page 2 the_empty_rlist = EmptyRList() @staticmethod def empty(): return RList.the_empty_rlist def init (self, first, rest=the_empty_rlist): self.first = first self.rest = rest def len (self): return 1 + len(self.rest) def getitem (self, i): if i == 0: return self.first return self.rest[i-1] def repr (self): # omitted for brevity def str (self): # omitted for brevity class EmptyRList(object): def repr (self): return RList.empty() def str (self): return <> def len (self): return 0 def getitem (self, k): raise IndexError( out of bounds: {0}.format(k)) 1.1 Python magic methods Just like init is the special method name that signals the class constructor, there are other method names that Python will handle specially. These include: len (self) Returns the length of this object. The len function will call the object s len method, if it s defined. getitem (self, i) Returns the element at index i. For instance, when you index into an object, like myobj[2], this is converted into the method call: myobj. getitem (i).

DISCUSSION 9: RLISTS AND THE ENVIRONMENT MODEL Page 3 repr (self) Returns a string representation of this object with the following rule: if you were to evaluate this string, then it would return the object. str (self) Returns some string representation of this object. This is much more relaxed than repr. There are many other magic methods in Python, which enable your user-defined classes to more-easily integrate with Python s built-in methods and objects 2. 1.2 Practice with RLists 1. (Warmup) Define a procedure map rlist that, given an RList rlist and a function fn, returns a new RList with all values in rlist mapped onto by fn. Don t modify the input RList. def map_rlist(rlist, fn): if rlist == RList.empty_rlist: return rlist else: return RList(fn(rlist.first), map_rlist(rlist.rest, fn)) 2 RLists and Mutation Because RList instances are mutable objects, we can modify them directly, instead of, say, creating a new RList when operating over them. For instance, we can mutate an RList by doing: >>> rlist = RList(3, RList(2, RList(1))) >>> rlist <3, 2, 1> >>> rlist.first = meow >>> rlist < meow, 2, 1> >>> rlist.rest.first = bark 2 Aside from the magic methods that we explicitly cover, you will not be responsible for knowing all of the magic methods

DISCUSSION 9: RLISTS AND THE ENVIRONMENT MODEL Page 4 >>> rlist < meow, bark, 1> >>> rlist.rest.rest = RList(RList( hi ), RList(42)) >>> rlist < meow, bark, << hi >, 42>> 2.1 More Practice with Rlists 1. (Warmup) Define a procedure map rlist that, given an RList rlist and a function fn, applies fn to every element in rlist. Your function should mutate the input rlist, and should not create any new RLists. def map_rlist(rlist, fn): if rlist == RList.empty(): return else: rlist.first = fn(rlist.first) map_rlist(rlist.rest, fn) 2. Now, define a procedure map rlist alt that works just like map rlist, but instead only applies the function to every other element, starting from the first. def map_rlist_alt(rlist, fn): if rlist == RList.empty(): return elif rlist.rest == RList.empty(): rlist.first = fn(rlist.first) else: rlist.first = fn(rlist.first) map_rlist_alt(rlist.rest.rest, fn)

DISCUSSION 9: RLISTS AND THE ENVIRONMENT MODEL Page 5 3 Environment Model of Evaluation In this topic, we will formally go over exactly how programs are executed in Python. In fact, it turns out that many other languages use the Environment Model of Evaluation. The main idea of the environment model is: All evaulation is done with respect to a frame. For instance, when you type expressions into the interpreter prompt, you are evaluating the expressions with respect to the global frame. On the other hand, expressions or statements that are evaluted within a function body is executed with respect to that function s local frame. A frame is a construct that contains two things: 1. All variable bindings that were declared in this frame. 2. An arrow to the parent frame that this frame extends. The global frame is special, in that all built-in functions and constants are defined here, such as abs, True, and pow. By definition, the global frame has no parent frame, and is the parent frame of all other frames. An environment is a series of frames, starting from the current frame to the global frame. You can generate the current environment by following parent pointers until you reach the global frame the set of frames that you passed through to get to the global frame consists of your current environment. Here is a concise list of how the Environment Model evaluates an expression: constants (numbers, strings, etc.) These are self-evaluating. variables Look up the variable name in the current frame. If it doesn t exist in the current frame, look in the parent frame (and the parent frame of that, etc.), and return the first value with the variable name. If you get to the global frame, and still haven t found the variable name, then signal an unbound variable error (called a NameError in Python). function definitions Create a new function object, and add the function binding to the current frame. function calls Evaluate the operands in the current frame. If the function is a primitive (built-in) procedure, then apply the function by magic. Otherwise, it s a user-defined function: create a new frame F. Bind fn s formal parameters to the evaluated operands values within F. Make F extend the current frame. Finally, evaluate fn s body with respect to the new frame F.

DISCUSSION 9: RLISTS AND THE ENVIRONMENT MODEL Page 6 3.1 Environment Diagrams In this course, we use Environment Diagrams to visually represent the Environment model. An environment diagram consists of two main objects: Boxes These represent your frames. Within each box, you ll write out all variable bindings. In addition, each box will have an arrow to its parent frame. You will only create a box when you call a user-defined function. At the very least, you will always have the Global frame present. Function Bubbles These represent user-defined functions. The left-bubble contains a list of its formal parameters, in addition to the body of the function. The right-bubble contains an arrow that points to the environment in which the function was created. You only create function bubbles when a function is created (either via def or lambda). In each of your environment diagrams, you ll always start with the global frame, but you need not include variable bindings for all built-in functions 3. As an example, here s the environment diagram for the following sequence of expressions: >>> honey = bear >>> mylst = [4, 2, 0] >>> def make_awesome(str1):... return awesome_ + str1 The interesting thing of note is the function bubble - this object represents the make awesome function. In particular, note that the right-bubble points to the global frame - this is because make awesome was defined in the global frame! Notice that no new frames have been created yet (we haven t called any user-defined functions yet!). But when we do call make awesome, the following new frame is created: 3 At times, you might find it helpful to include some built-in functions in your diagrams see the environment diagram exercise 2.f for an example. If you do, instead of creating a lambda bubble for the built-in functions, use some distinguishing object that signals that this is a built-in function object, not a user-defined function object.

DISCUSSION 9: RLISTS AND THE ENVIRONMENT MODEL Page 7 >>> result = make_awesome(honey) 3.2 Practice with Environment Diagrams Note: For the following solution diagrams, the author omitted the function bodies from the left-bubble of each lambda bubble. This was purely done for brevity in your own diagrams (say, on an exam), you should still put at least an abridged version of the function body. 1. (Warmup) Draw the environment diagram of the following expressions: a = lambda x: x*2 + 1 def b(x): return x * y y = 3 b(y) # What is the return value?

DISCUSSION 9: RLISTS AND THE ENVIRONMENT MODEL Page 8 Returns: 9 a = lambda x: x*2 + 1 b = lambda x: x * y y = 3 def c(x): y = a(x) return b(x) + a(x+y) c(y) # What is the return value?

DISCUSSION 9: RLISTS AND THE ENVIRONMENT MODEL Page 9 2. Draw the environment diagram at the indicated locations. If an error occurs, write ERROR: def square(x): return x * x def call_it(fn, n): return fn(n) n = 22 call_it(square, n-2) # What is the return value?

DISCUSSION 9: RLISTS AND THE ENVIRONMENT MODEL Page 10 def make_adder(x): return lambda y: x + y add_4 = make_adder(4) add_4(5) # What is the return value? mylst = [1, 2, yay ] def modify_it_maybe(lst):

DISCUSSION 9: RLISTS AND THE ENVIRONMENT MODEL Page 11 lst = [ this, is, crazy ] return lst result = modify_it_maybe(mylst) result[2] = awesome mylst[0] = wat val = 3 square = lambda x: x * x def foo(fn, val): def doit(): return fn(val) return doit f = foo(square, 4) f() # What is the return value?

DISCUSSION 9: RLISTS AND THE ENVIRONMENT MODEL Page 12 from operator import add, sub def f(add, sub): return add((lambda sub: sub(3, 5))(sub), 10) f(sub, add) # What is the return value?

DISCUSSION 9: RLISTS AND THE ENVIRONMENT MODEL Page 13 def hmm(n): return lambda x: x + y + n def uhh(y): hmm_y = hmm(y) return hmm_y(2) uhh(42) # What is the return value?

DISCUSSION 9: RLISTS AND THE ENVIRONMENT MODEL Page 14