CONTROL AND HIGHER ORDER FUNCTIONS 1

Similar documents
CONTROL AND HIGHER ORDER FUNCTIONS 2

C ONTROL AND H IGHER O RDER F UNCTIONS

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

CONTROL AND ENVIRONMENTS 1

HIGHER ORDER FUNCTIONS AND ENVIRONMENT DIAGRAMS 2

CONTROL AND HIGHER ORDER FUNCTIONS 1

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

HIGHER-ORDER FUNCTIONS 2

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

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

ENVIRONMENT DIAGRAMS AND RECURSION 2

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

ENVIRONMENT DIAGRAMS AND RECURSION 2

EXPRESSIONS, STATEMENTS, AND FUNCTIONS 1

61A Lecture 4. Monday, September 9

61A Lecture 3. Friday, September 5

functional programming in Python, part 2

HIGHER ORDER FUNCTIONS 2

Midterm Exam 1 Solutions

Structure and Interpretation of Computer Programs Fall 2012 Alternate Midterm 1

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

Structure and Interpretation of Computer Programs

Measuring Efficiency

Structure and Interpretation of Computer Programs

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

Control Flow: Loop Statements

61A Lecture 6. Friday, September 7

RECURSION: n. SEE RECURSION 3

Test #2 October 8, 2015

1 Truth. 2 Conditional Statements. Expressions That Can Evaluate to Boolean Values. Williams College Lecture 4 Brent Heeringa, Bill Jannen

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

Statements 2. a operator= b a = a operator b

Lecture 7: Primitive Recursion is Turing Computable. Michael Beeson

Introduction to Functional Programming (Python) John R. Woodward

Organization of Programming Languages CS3200/5200N. Lecture 11

CS 1301 CS1 with Robots Summer 2007 Exam 1

CSCE 110: Programming I

Conditionals and Recursion. Python Part 4

Structure and Interpretation of Computer Programs Fall 2015 Midterm 1

61A Lecture 2. Wednesday, September 4, 2013

Introduction to Programming II W4260. Lecture 2

DM536 / DM550 Part 1 Introduction to Programming. Peter Schneider-Kamp.

Programming. We will be introducing various new elements of Python and using them to solve increasingly interesting and complex problems.

Chapter 15 Functional Programming Languages

STATS 507 Data Analysis in Python. Lecture 2: Functions, Conditionals, Recursion and Iteration

Loops and Conditionals. HORT Lecture 11 Instructor: Kranthi Varala

61A Lecture 2. Friday, August 28, 2015

Control Structures 1 / 17

Structure and Interpretation of Computer Programs

61A LECTURE 7 DATA ABSTRACTION. Steven Tang and Eric Tzeng July 3, 2013

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming

CPSC 3740 Programming Languages University of Lethbridge. Control Structures

DM536 Introduction to Programming. Peter Schneider-Kamp.

Midterm 1 Review. Important control structures. Important things to review. Functions Loops Conditionals

Functions and Recursion

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

CS1 Lecture 5 Jan. 26, 2018

Part 1 (80 points) Multiple Choice Questions (20 questions * 4 points per question = 80 points)

FP Foundations, Scheme

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

Documentation for LISP in BASIC

Conditionals: Making Choices

CSM Mock Final Spring 2018

Lecture #3: Environments

Structure and Interpretation of Computer Programs

CSSE 120 Introduction to Software Development Practice for Test 1 paper-and-pencil part Page 1 of 6

ANS:

CS1 Lecture 5 Jan. 25, 2019

DM502 Programming A. Peter Schneider-Kamp.

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

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

Some Sample AP Computer Science A Questions - Solutions

2. Explain the difference between read(), readline(), and readlines(). Give an example of when you might use each.

Lecture #11: Immutable and Mutable Data. Last modified: Sun Feb 19 17:03: CS61A: Lecture #11 1

DM502 Programming A. Peter Schneider-Kamp.

Structure and Interpretation of Computer Programs

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

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

Functionally Modular. Self-Review Questions

Programming to Python

Comp 150 Final Exam Overview.

Chapter 1. Fundamentals of Higher Order Programming

Flow Control: Branches and loops

Python - Conditional Execution

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

Iteration. # a and b are now equal # a and b are no longer equal Multiple assignment

Lecture 21: Functional Programming in Python. List Comprehensions

PLT Fall Shoo. Language Reference Manual

CS1 Lecture 3 Jan. 18, 2019

Fundamentals of Programming. Week 1 - Lecture 3: Loops

Condition-Controlled Loop. Condition-Controlled Loop. If Statement. Various Forms. Conditional-Controlled Loop. Loop Caution.

And Parallelism. Parallelism in Prolog. OR Parallelism

RECURSION, RECURSION, (TREE) RECURSION! 2

DM550/DM857 Introduction to Programming. Peter Schneider-Kamp

Programming Languages

CS1 Lecture 3 Jan. 22, 2018

DECOMPOSITION, ABSTRACTION, FUNCTIONS

Outline. 1 If Statement. 2 While Statement. 3 For Statement. 4 Nesting. 5 Applications. 6 Other Conditional and Loop Constructs 2 / 19

02157 Functional Programming Lecture 2: Functions, Basic Types and Tuples

Transcription:

CONTROL AND HIGHER ORDER FUNCTIONS 1 COMPUTER SCIENCE 61A January 29, 2015 1 Control Control structures direct the flow of logic in a program. For example, conditionals allow a program to skip sections of code, while iteration allows a program to repeat a section. 1.1 Conditional Statements Conditional statements let programs execute different lines of code depending on certain conditions. In Python, we can use the if- elif-else block: if <conditional expression>: <suite of statements> elif <conditional expression>: <suite of statements> else: <suite of statements> Some notes: The else and elif statements are optional. You can have any number of elif statements. A conditional expression is a Python expression. whether its value is a true value or a false value. All that matters for control is The code that is executed is the suite that is indented under the first if/elif that has a true conditional expression. If none are true, then the else suite is executed. Once one suite is executed, the rest are skipped. 1

DISCUSSION 1: CONTROL AND HIGHER ORDER FUNCTIONS Page 2 Note: in Python, there are a few things that are treated as false values: The boolean False The integer 0 The value None And more... Python also includes boolean operators and, or, and not. These operators are used to combine and manipulate boolean values. not True evaluates to False, and not False evaluates to True. True and True evaluates to True, but a false value on either side makes it False. False or False evaluates to False, but a true value on either side makes it True. 1.2 Iteration Iteration lets a program repeat statements multiple times. A common iterative block of code is the while loop: while <conditional clause>: <body of statements> This block of code states: while the conditional clause is still True, continue executing the indented body of statements. Here is an example: >>> def countdown(x):... while x > 0:... print(x)... x = x - 1... print("blastoff!")... >>> countdown(3) 3 2 1 Blastoff! 1.3 Questions 1. Fill in the is prime function, which returns True if n is a prime number and False otherwise. Hint: use the % operator: x % y returns the remainder of x when divided by y.

DISCUSSION 1: CONTROL AND HIGHER ORDER FUNCTIONS Page 3 def is_prime(n): 1.4 Extra Questions 1. Fill in the choose function, which returns the number of ways to choose k items from n items. Mathematically, choose(n, k) is defined as: n (n 1) (n 2) (n k + 1) k (k 1) (k 2) 2 1 def choose(n, k): Returns the number of ways to choose K items from N items. >>> choose(5, 2) 10 >>> choose(20, 6) 38760

DISCUSSION 1: CONTROL AND HIGHER ORDER FUNCTIONS Page 4 2 Higher Order Functions A function that manipulates other functions is called a higher order function (HOF), which is a function that takes functions as arguments, returns a function, or both. 2.1 Functions as Argument Values Suppose we want to square or double every integer from 1 to n and print the result as we go. Fill in the functions square ints and double ints by using the square and double functions we have defined. def square(x): return x * x def square_ints(n): Print out the square of every integer from 1 to n. >>> square_ints(3) 1 4 9 def double(x): return 2 * x def double_ints(n): Print out the double of every integer from 1 to n. >>> double_ints(3) 2 4 6 The only difference between square ints and double ints is the function called before printing (either square or double).

DISCUSSION 1: CONTROL AND HIGHER ORDER FUNCTIONS Page 5 It would be nice to have a generalized function, transform ints, that took care of the while loop and the incrementing for us. That way, we could triple ints or cube ints without repeating so much code: def square_ints(n): transform_ints(square, n) def double_ints(n): transform_ints(double, n) def cube(x): return x * x * x def cube_ints(n): transform_ints(cube, n) 2.2 Questions 1. Implement the function transform ints that takes in a function func and a number n and prints the result of applying that function to each of the first n natural numbers. def transform_ints(func, n): Print out all integers from 1 to n with func applied on them. >>> def square(x):... return x * x >>> transform_ints(square, 3) 1 4 9

DISCUSSION 1: CONTROL AND HIGHER ORDER FUNCTIONS Page 6 2.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 Note two things: 1. The return value of the outer function is inner. This is where a function returns a function. 2. In this case, the inner function is defined inside of the outer function. This is a common pattern, but it is not necessary; we could have defined inner outside of the outer and still use the same return statement. 2.4 Questions 1. Write a function and add that takes a function f (such that f is a function of one argument) and a number n as arguments. It should return a function that takes one argument, and does the same thing as the function f, except also adds n to the result. def and_add(f, n): Return a new function. This new function takes an argument x and returns f(x) + n. >>> def square(x):... return x * x >>> new_square = and_add(square, 3) >>> new_square(4) # 4 * 4 + 3 19

DISCUSSION 1: CONTROL AND HIGHER ORDER FUNCTIONS Page 7 2. Draw the environment diagram that results from running the following code: n = 7 def f(x): n = 8 return x + 1 def g(x): n = 9 def h(): return x + 1 return h def f(f, x): return f(x + n)() m = f(g, n) 2.5 Extra Questions 1. 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

DISCUSSION 1: CONTROL AND HIGHER ORDER FUNCTIONS Page 8 2. The following code has been loaded into the Python interpreter: def skipped(f): def g(): return f return g def composed(f, g): def h(x): return f(g(x)) return h def added(f, g): def h(x): return f(x) + g(x) return h def square(x): return x*x def two(x): return 2 What will Python output when the following lines are evaluated? >>> composed(square, two)(7) >>> skipped(added(square, two))()(3) >>> composed(two, square)(2) 3. 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 1: CONTROL AND HIGHER ORDER FUNCTIONS Page 9 3 Addendum: Environment Diagrams An environment diagram helps visualize the Python environment when a program is executed. The environment consists of a stack of frames, which contain variables and the values bound to them. x = 2 def square(x): return x ** 2 square(2) 3.1 Questions 1. Draw the environment diagram that results from running the following code. a = 1 def b(b): return a + b a = b(a) a = b(a)

DISCUSSION 1: CONTROL AND HIGHER ORDER FUNCTIONS Page 10 2. Draw the environment diagram that results from executing the code below. def this(x): return 2*that(x) def that(x): x = y + 1 this = that return x x, y = 1, 2 this(that(y)) 3.2 Extra Questions 1. Draw the environment diagram that results from executing the code below. from operator import add, mul six = 2 def ty(one, a): spring = one(a, six) return spring def fif(teen): return teen ** 2 six = ty(add, mul(six, six)) spring = fif(six)