HIGHER ORDER FUNCTIONS AND ENVIRONMENT DIAGRAMS 2

Similar documents
HIGHER-ORDER FUNCTIONS 2

CS 61A Higher Order Functions and Recursion Fall 2018 Discussion 2: June 26, Higher Order Functions. HOFs in Environment Diagrams

CS 61A Higher Order Functions and Recursion Fall 2018 Discussion 2: June 26, 2018 Solutions. 1 Higher Order Functions. HOFs in Environment Diagrams

CONTROL AND HIGHER ORDER FUNCTIONS 1

CS 61A Control and Environments Spring 2018 Discussion 1: January 24, Control. If statements. Boolean Operators

ENVIRONMENT DIAGRAMS AND RECURSION 2

C ONTROL AND H IGHER O RDER F UNCTIONS

CONTROL AND ENVIRONMENTS 1

Environment Diagrams and Recursion Fall 2017 Discussion 2: September 6, 2017 Solutions. 1 More Environment Diagrams

CONTROL AND HIGHER ORDER FUNCTIONS 1

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

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

CONTROL AND HIGHER ORDER FUNCTIONS 2

ENVIRONMENT DIAGRAMS AND RECURSION 2

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

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

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

61A Lecture 4. Monday, September 9

CS 61A Interpreters, Tail Calls, Macros, Streams, Iterators. Spring 2019 Guerrilla Section 5: April 20, Interpreters.

functional programming in Python, part 2

Programming Languages

UNIVERSITY OF CALIFORNIA Department of Electrical Engineering and Computer Sciences Computer Science Division. P. N. Hilfinger

DRAWING ENVIRONMENT DIAGRAMS

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

Structure and Interpretation of Computer Programs Spring 2017 Mock Midterm 1

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

April 2 to April 4, 2018

Structure and Interpretation of Computer Programs

Scheme: Strings Scheme: I/O

Working with Lists 4

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

Exercise 1 ( = 24 points)

HIGHER ORDER FUNCTIONS 2

Lecture 16: Static Semantics Overview 1

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

Structure and Interpretation of Computer Programs

Lecture #5: Higher-Order Functions. A Simple Recursion. Avoiding Recalculation. Redundant Calculation. Tail Recursion and Repetition

11/6/17. Functional programming. FP Foundations, Scheme (2) LISP Data Types. LISP Data Types. LISP Data Types. Scheme. LISP: John McCarthy 1958 MIT

Every language has its own scoping rules. For example, what is the scope of variable j in this Java program?

ENVIRONMENT MODEL: FUNCTIONS, DATA 18

CSCI B522 Lecture 11 Naming and Scope 8 Oct, 2009

User-defined Functions. Conditional Expressions in Scheme

Structure and Interpretation of Computer Programs Fall 2015 Midterm 1

CS 61B Midterm 1 Guerrilla Section Spring 2018 February 10, 2018

Structure and Interpretation of Computer Programs Fall 2012 Alternate Midterm 1

Harvard School of Engineering and Applied Sciences CS 152: Programming Languages. Lambda calculus

Problem Solving for Intro to Computer Science

Structure and Interpretation of Computer Programs

Lecture 07, Fall 2018 Wednesday September 19

Department of Electrical Engineering and Computer Science MASSACHUSETTS INSTITUTE OF TECHNOLOGY

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

Programming Languages. Thunks, Laziness, Streams, Memoization. Adapted from Dan Grossman s PL class, U. of Washington

# true;; - : bool = true. # false;; - : bool = false 9/10/ // = {s (5, "hi", 3.2), c 4, a 1, b 5} 9/10/2017 4

Booleans (aka Truth Values) Programming Languages and Compilers (CS 421) Booleans and Short-Circuit Evaluation. Tuples as Values.

CSE341 Spring 2017, Final Examination June 8, 2017

Scheme: Data. CS F331 Programming Languages CSCE A331 Programming Language Concepts Lecture Slides Monday, April 3, Glenn G.

61A Lecture 6. Friday, September 7

Section 05: Solutions

Structure and Interpretation of Computer Programs

CS152: Programming Languages. Lecture 7 Lambda Calculus. Dan Grossman Spring 2011

Structure and Interpretation of Computer Programs

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

Python review. 1 Python basics. References. CS 234 Naomi Nishimura

PAIRS AND LISTS 6. GEORGE WANG Department of Electrical Engineering and Computer Sciences University of California, Berkeley

Math 15 - Spring Homework 5.2 Solutions

CS 61B Midterm 1 Guerrilla Section Spring 2018 February 10, 2018

The SPL Programming Language Reference Manual

;; definition of function, fun, that adds 7 to the input (define fun (lambda (x) (+ x 7)))

Programming Languages. Streams Wrapup, Memoization, Type Systems, and Some Monty Python

MUTABLE LISTS AND DICTIONARIES 4

Overview of List Syntax

Structure and Interpretation of Computer Programs

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

Continuations and Continuation-Passing Style

Data Structures and Algorithms Dr. Naveen Garg Department of Computer Science and Engineering Indian Institute of Technology, Delhi.

CSE341 Spring 2017, Final Examination June 8, 2017

Midterm II CS164, Spring 2006

DECOMPOSITION, ABSTRACTION, FUNCTIONS

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

Defining Functions III: Nested Definitions

Encodings. Using the minimal λ-calculus language we get. functions. local binding. booleans. numbers... and recursive functions?

Programming Languages

Honors Computer Science Python Mr. Clausen Programs 4A, 4B, 4C, 4D, 4E, 4F

Com S 127x - Lab 6 1. READING FLOWCHARTS WITH CONDITIONAL ACTIONS!

CSCI337 Organisation of Programming Languages LISP

CS61C Machine Structures. Lecture 4 C Pointers and Arrays. 1/25/2006 John Wawrzynek. www-inst.eecs.berkeley.edu/~cs61c/

Warm-up and Memoization

Structure and Interpretation of Computer Programs

Sample Final Exam Questions

CS558 Programming Languages

Functional programming in LISP

Lists, loops and decisions

Structure and Interpretation of Computer Programs

CS115 - Module 9 - filter, map, and friends

1. What type of error produces incorrect results but does not prevent the program from running? a. syntax b. logic c. grammatical d.

cs61amt2_4 CS 61A Midterm #2 ver March 2, 1998 Exam version: A Your name login: cs61a- Discussion section number TA's name

Learning the Language - V

Structure and Interpretation of Computer Programs Summer 2014 Midterm 1

Data 8 Final Review #1

Functional Programming

Transcription:

HIGHER ORDER FUNCTIONS AND ENVIRONMENT DIAGRAMS 2 COMPUTER SCIENCE 61A June 25, 2015 1 Higher Order Functions A higher order function (HOF) is a function that manipulates other functions by taking in functions as arguments, returning a function, or both. 1.1 Functions as Arguments One way a higher order function can exploit other functions is by taking functions as input. Consider this higher order function called negate. def negate(f, x): return -f(x) negate takes in a function f and a number x. It doesn t care what exactly f does, as long as f takes in a number and returns a number. Its job is simple: call f on x and return the negation of that value. 1.2 Questions 1. Here are some possible functions that can be passed through as f. def square(n): return n * n def double(n): return 2 * n What will the following Python statements output? 1

DISCUSSION 2: HIGHER ORDER FUNCTIONS AND ENVIRONMENT DIAGRAMS Page 2 >>> negate(square, 5) >>> negate(double, -19) >>> negate(double, negate(square, -4)) 2. Implement a function keep ints, which takes in a function cond and a number n, and only prints a number from 1 to n if calling cond on that number returns True: def keep_ints(cond, n): """Print out all integers 1..i..n where cond(i) is true >>> def is_even(x):... # Even numbers have remainder 0 when divided by 2.... return x % 2 == 0 >>> keep_ints(is_even, 5) 2 4 """ 1.3 Functions as Return Values Often, we will need to write a function that returns another function. One way to do this is to define a function inside of a function: def outer(x): def inner(y):... return inner The return value of outer is the function inner. This is a case of a function returning a function. In this example, inner is defined inside of outer. Although this is a common pattern, we can also define inner outside of outer and still use the same return statement. def inner(y):... def outer(x): return inner

DISCUSSION 2: HIGHER ORDER FUNCTIONS AND ENVIRONMENT DIAGRAMS Page 3 1.4 Questions 1. Use this definition of outer to fill in what Python would print when the following lines are evaluated. def outer(n): def inner(m): return n - m return inner >>> outer(61) >>> f = outer(10) >>> f(4) >>> outer(5)(4) 2. Implement a function keep ints like before, but now it takes in a number n and returns a function that has one parameter cond. The returned function prints out all numbers from 1..i..n where calling cond(i) returns True. def keep_ints(n): """Returns a function which takes one parameter cond and prints out all integers 1..i..n where calling cond(i) returns True. >>> def is_even(x):... # Even numbers have remainder 0 when divided by 2.... return x % 2 == 0 >>> keep_ints(5)(is_even) 2 4 """ 2 Lambda Functions Lambda expressions are one-line functions that specify two things: the parameters and the return expression.

DISCUSSION 2: HIGHER ORDER FUNCTIONS AND ENVIRONMENT DIAGRAMS Page 4 A lambda expression that takes in no arguments and returns 8: lambda: 8 }{{} return value A lambda expression that takes two arguments and returns their product: lambda x, y }{{} : x * y }{{} parameters return expression Unlike functions created by a def statement, the function object that a lambda expression creates has no intrinsic name and is not bound to any variable. In fact, nothing changes in the current environment when we evaluate a lambda expression unless we do something with this expression, such as assign it to a variable or pass it as an argument to a higher order function. 2.1 Questions 1. What would Python print? >>> a = lambda: 5 >>> a() >>> a(5) >>> b = lambda: lambda x: 3 >>> b()(15) >>> c = lambda x, y: x + y >>> c(4, 5) >>> d = lambda x: lambda y: x * y >>> d(3) >>> d(3)(3) >>> e = d(2) >>> e(5) >>> f = lambda: print(1) >>> g = f()

DISCUSSION 2: HIGHER ORDER FUNCTIONS AND ENVIRONMENT DIAGRAMS Page 5 2. Fill in the blanks with one-line lambda expressions so that each call expression that follows returns 3. >>> f1 = >>> f1() 3 >>> f2 = >>> f2()() 3 >>> f3 = >>> f3()(3) 3 >>> f4 = >>> f4()()(3)() 3

DISCUSSION 2: HIGHER ORDER FUNCTIONS AND ENVIRONMENT DIAGRAMS Page 6 3 Environment Diagrams Recall that an environment diagram keeps track of all the variables that have been defined and the values they are bound to. However, values are not necessarily only integers and strings. Environment diagrams can model more complex programs that utilize higher order functions. def add_num(x): return lambda y: x + y add_two = add_num(2) add_two(3) Lambdas are represented similiarly to functions in environment diagrams, but since they lack an instrinsic name, the lambda symbol (λ) is used instead. The parent of a function, including lambdas, is always the frame in which the function is defined. It is useful to include the parent in environment diagrams in order to find variables that are not defined in the current frame. In the previous example, when we call add two (which is really the lambda function), we need to know what x is in order to compute x + y. Since x is not in the frame f2, we look at the frame s parent, which is f1. There, we find x is bound to 2. As illustrated above, higher order functions that return a function are represented with a pointer to the function object.

DISCUSSION 2: HIGHER ORDER FUNCTIONS AND ENVIRONMENT DIAGRAMS Page 7 3.1 Questions 1. Draw the environment diagram that results from executing the code below. from operator import add six = 1 def ty(one, a): spring = one(a, six) return spring six = ty(add, 6) spring = ty(add, 6)

DISCUSSION 2: HIGHER ORDER FUNCTIONS AND ENVIRONMENT DIAGRAMS Page 8 2. Draw the environment diagram for the following code: from operator import add def curry2(h): def f(x): def g(y): return h(x, y) return g return f make_adder = curry2(add) add_three = make_adder(3) five = add_three(2)

DISCUSSION 2: HIGHER ORDER FUNCTIONS AND ENVIRONMENT DIAGRAMS Page 9 3.2 Extra Questions 1. Draw the environment diagram for the following code: (Note that using the + operator with two strings results in the second string being appended to the first. For example "C" + "S" concatenates the two strings into one string "CS") y = "y" h = y def y(y): h = "h" if y == h: return y + "i" y = lambda y: y(h) return lambda h: y(h) y = y(y)(y)