What Are Programs?
CS 61A Midterm 1 Study Guide – Page 1
Pure Functions
208
mul:
...
mul(add(2, mul(4, 6)), add(3, 5))
square(x):
return mul(x, x)
26
8
add(2, mul(4, 6))
add(3, 5)
mul
add
2
3
return mul(x, x)
1024
from operator import mul
def square(x):
return mul(x, x)
square(-2)
-2
mul
4
6
mul:
Wednesday,
October 12
...
mul(a,b):
Environments
& Values
square:
square(x):
return mul(x, x)
Expressions
x: -2
print(...):
None
display “-2”
Formal parameter
Return
Defining:
expression
>>> def square( x ):
A name evaluates
return mul(x, x)
Def
to the value
statement
bound to that
name in the
The environment
Body (return statement)
earliest frame
Pure Functions
created for the
4
of the current
208
function body
square(-2)
environment in
mul(add(2, mul(4, 6)), add(3, 5))
-2
abs(number): Call expression: square(2+2) operand: 2+2
which that name
argument: 4
2
return mul(x, x)
operator: square
is found.
function: square
8
2, 10
pow(x, y):
mul
26
Environments
(Names):
mul:
1024
The 6))
global
add(3, 5)
add(2, mul(4,
Calling/Applying:
...
frame
4
Frames link to each other
square( x ):
Argument
Non-Pure
Functions
An environment
is a sequence
return mul(x, x) 16
add of 3frames5
add
2
24
Intrinsic name
Local
print(...):
Return value
x:
An environment is -2
a first
frame,
mul(4, 6)
frame
None
plus the environment that follows
The existing environment in which
the call expression is evaluated
CS 61A Midterm 1 Study Guide – Page 1
pow(x, y):
5
mul(4, 6)
4
Binding
Name
a:
2
b:
5
Value
Frame
Environment
mul:
...
The global
frame
Local
x:
frame
Now, we type programs
as text files using editors like Emacs
square
4
square(-2)
return mul(x, x)
from operator import mul
def square(x):
return mul(x, x)
square(-2)
The existing environment in which
the call expression is evaluated
The environment
created for the
function body
4
square(-2)
return mul(x, x)
The global
frame
A name evaluates
to the value
bound to that
name in the
earliest frame
of the current
environment in
which that name
is found.
Environments (Names):
Frames link to each other
An environment is a sequence
of frames
x:
add
24
square
mul:
...
2, 10
Every once Non-Pure
in aFunctions
while, they would "punch in" a program
Expressions
x: -2
square(-2)
abs(number):
Once upon a time, people wrote programs on blackboards
Environments
& Values
square:
61A Lecture 19
-2
2
mul(a,b):
Local
frame
An environment is a first frame,
plus the environment that follows
Not part of an environment
2
mul:
Programs are just text (or cards) until we interpret them
...
mul(a,b):
4
Value
return mul(x, x)
They are evaluated in an
environment to yield a value
Return expression
Evaluation rule for call expressions:
1.Evaluate the operator and operand subexpressions.
2.Apply the function that is the value of the operator
subexpression to the arguments that are the values of the
operand subexpressions.
Applying user-defined functions:
1.Create a new local frame that extends the environment with
which the function is associated.
2.Bind the arguments to the function's formal parameter
names in that frame.
3.Execute the body of the function in the environment
beginning at that frame.
Execution rule for def statements:
(return
1.Evaluate the Body
operator
and statement)
operand subexpressions.
x: 3
Frame
2.Apply the function that is the value of the operator
square
subexpression to the arguments that are the values of the
Call expression:
square(2+2) operand: 2+2
operand subexpressions.
Environment
argument: 4
Applying
user-defined functions:
operator:
square
function:
square
1.Create
a new local frame that extends the environment with
mul:
The global
which the function is associated.
...
frame
2.Bind the arguments to the function's formal parameter
Calling/Applying:
names in that4 frame.
square( x ):
3.Execute
the body of the function in the environment
Argument
return mul(x, x) 16
beginning at that frame.
Local
x:
Intrinsic
mul:
Execution
rule name
for def statements:
frame
Return value
1.Create a new function value with the specified name,
formal parameters, and function body.
2.Associate that function
with the
currentof
environment.
square:
Both outlined
sequences
frames are environments
3.Bind the name of the function to the function value in the
mul:
first frame of the current environment.
square
81
square(square(3))
Execution rule for conditional statements:
Each clause is considered in order.
1.Evaluate the header's expression.
2.If it is a true value, execute the suite, then skip the
remaining clauses in the statement.
Evaluation rule for or expressions:
1.Evaluate the subexpression <left>.
2.If the result is a true value v, then the expression
evaluates to v.
3.Otherwise, the expression evaluates to the value of the
subexpression <right>.
Evaluation rule for and expressions:
1.Evaluate the subexpression <left>.
2.If the result is a false value v, then the expression
evaluates to v.
3.Otherwise, the expression evaluates to the value of the
subexpression <right>.
Evaluation rule for not expressions:
9
square(3)
def square(square):
return mul(square, square)
from operator import mul
square(4)
mul(a,b):
square(square):
Designing Interpreters
Page 2
Common elements: User-defined functions & call expressions
Some features are often excluded: Higher-order functions,
object systems, while and for statements, assignment, etc.
1. Evaluate
the header’s expression.
square:
4
2. If it is a true value, execute the (whole) suite, then
square
to step 1.
Environments & Values
Expressions
16
return square(4)
total
return pow(k, the
3)
An interpreter, which determines
meaning
A formal parameter that
will be bound to a function
def summation(n, term):
of expressions in a programming
language,
"""Sum the first n terms of a sequence.
is just another program.
3
3
3
3
5
3
3
3
3
5
The function bound to term
Raw code is passed around like data.
def make_adder(n):• Recursive functions
"""Return a function that takes one argument k and returns k + n.
Function of a single
argument (not called term)
>>> summation(5, cube)
225
The cube function is passed
"""
as an argument value
total, k = 0, 1
while k <= n:
total, k = total + term(k), k + 1
return total
return total
Before we
buildfunctions
interpreters:
# Local function definitions;
returning
return mul(square, square)
def cube(k):
Coming soon: The Logo language doesn't include any of these
features, but still lets us define short, powerful programs!
0 + 1 + 2 + 3 + 4 +How
5
can
be?
gets that
called here
def
pi_term(k):
return 8 / (k * 4 é 3) / Page
(k * 24 é 1)
return
hof.py
def identity(k):
The most fundamental idea
in computer
science:
return
k
1.Evaluate <exp>; The value is True if the result is a false
value, and False otherwise.
Execution rule for while statements:
1. Evaluate the header’s expression.
2. If it is a true value, execute the (whole) suite, then
return to step 1.
2
All programming languages are not the same!
Nested def statements: Functions defined within other
function bodies are bound to names in the local frame
Execution rule for assignment statements:
1.Evaluate the expression(s) on the right of the equal sign.
2.Simultaneously bind the names on the left to those values
in the first frame of the current environment.
Every call to a userdefined function creates
a new local frame
x: 9
<header>:
<statement>
Suite
<statement>
...
<separating header>:
<statement>
<statement>
...
...
Execution
rule for assignment
mul(a,b): statements:
...
return mul(square, square)
statement
1.Evaluate the expression(s) on the right of Compound
the equal
sign.
Clause 4
square:
square:
2.Simultaneously
bind the names on the left to those values
in the first frame of the current environment.
square
Environments & Values
square(x):
<header>:
hof.py
Execution rule for conditional statements:
Expressions
<statement>
16
Each clause is considered in order.
Suite
<statement>
Every call
to a userreturn square(4)
total
expression.
x: 1.Evaluate
3
x: 9 the header's
...
defined
2.If it is a true
value,function
execute creates
the suite, then
skip theheader>:
<separating
square
square
a new
frame
return mul(square, square)
remaining clauses in
the local
statement.
def identity(k):
<statement>
Evaluation rule for or expressions:
return k
<statement>
81
1.Evaluate the subexpression
<left>.
...
2.If the result
is a true value v, then the expression
square(square(3))
Function of a single
...
def cube(k):
evaluates to v.
argument (not called term)
return pow(k, 3)
3.Otherwise, the expression
evaluates
to
the
value
of
the
9
A formal parameter that
subexpression <right>.
square(3)
Evaluation rule for and expressions:
def summation(n, term):will be bound to a function
1.Evaluate the subexpression <left>.
"""Sum the first n terms of a sequence.
def square(square):
2.If the result is a false value v, then the expression
return mul(square, square)
mul:
evaluates to v.
from operator import mul
>>> summation(5, cube)
3.Otherwise,mul(a,b):
the expression evaluates to the value of the
square(4)
225
subexpression <right>.
The cube function is passed
"""
square:
Evaluation rule for not expressions:
as an argument value
total, k = 0, 1
1.Evaluate <exp>;
The value is True if the result is a false
square(square):
while k <= n:
value, and False otherwise.
total, k = total + term(k), k + 1
return
Execution rule for
whilemul(square,
statements:square)
Higher-order function: A function that takes a function as an
argument value or returns a function as a return value
1.Create a new function value with the specified name,
formal parameters, and function body.
2.Associate that function with the current environment.
3.Bind the name of the function to the function value in the
first frame of the current environment.
Clause
http://en.wikipedia.org/wiki/File:IBM_Port-A-Punch.jpg
square(x):
5
How Are Evaluation Procedures Applied?
square( 2 )
Compound statement
square:
Value
Nested def statements: Functions defined within other
function bodies are bound to names in the local frame
Expressions (Program):
Both outlined sequences of frames are environments
Expressions (Program): display “-2”
Higher-order function: A function that takes a function as an
argument value or returns a function as a return value
Call expression
mul
4
6
Call expression
Not part of an environment
4 parameter
Formal
Binding
They
are evaluated in an
Return
Value
Defining: square( 2 )
environment to yield a value
expression
>>> def square( x ):
a:
return mul(x, x)
Return expression Name
return mul(x, x)
Def
b:
statement
Evaluation rule for call expressions:
3
>>> add_three •= Recursive
make_adder(3) data
>>> add_three(4)
7
• Error handling
"""
def adder(k):
return k + n
return adder
structures
def compose1(f, g):
"""Return a function that composes f and g.
4
f, g éé functions of a single argument
"""
def h(x):
return f(g(x))
return h
The function bound to term
gets called here
0 + 1 + 2 + 3 + 4 + 5
def
pi_term(k):
return 8 / (k * 4 é 3) / (k * 4 é 1)
# Local function definitions; returning functions
@main
def make_adder(n):
def run():
"""Return a function that takes one argument k andinteract()
returns k + n.
Recursive Functions
>>> add_three = make_adder(3)
>>> add_three(4)
7
"""
def adder(k):
return k + n
return adder
Example: Pig Latin
def compose1(f, g):
"""Return a function that composes f and g.
Definition: A function is called recursive
if the body of that
f, g éé functions of a single argument
"""
function calls itself, either directly
or indirectly.
Yes, you're in a college class and learning Pig Latin.
def h(x):
return f(g(x))
return h
def pig_latin(w):
Implication: Executing the body of a recursive function may
require applying that function again.
@main
"""Return the Pig Latin equivalent of English word w."""
def run():
interact()
if starts_with_a_vowel(w):
return w + 'ay'
return pig_latin(w[1:] + w[0])
def starts_with_a_vowel(w):
"""Return whether w begins with a vowel."""
return w[0].lower() in 'aeiou'
Demo
Drawing Hands, by M. C. Escher (lithograph, 1948)
5
6
Environments for Pig Latin
The Anatomy of a Recursive Function
if starts_with_a_vowel(w):
return w + 'ay'
return pig_latin(w[1:] + w[0])
starts_with_a_vowel:
Recursive functions are
like ants (more or less)
• Conditional statements check
for base cases
• Base cases are evaluated
without recursive calls
starts_with_a_vowel(w):
w: 'pun'
w: 'unp'
• The def statement header is
similar to other functions
pig_latin(w):
pig_latin:
return w[0].lower() in 'aeiou'
• Typically, all other cases are
evaluated with recursive calls
'unpay'
pig_latin('pun')
if starts_with_a_vowel(w):
return w + 'ay'
return pig_latin(w[1:] + w[0])
def pig_latin(w):
if starts_with_a_vowel(w):
'unpay'
return w + 'ay'
pig_latin(w[1:] + w[0])
return pig_latin(w[1:] + w[0])
if starts_with_a_vowel(w):
return w + 'ay'
return pig_latin(w[1:] + w[0])
http://en.wikipedia.org/wiki/File:Scheme_ant_worker_anatomy-en.svg
7
Iteration vs Recursion
8
Environments for Factorial
Iteration is a special case of recursion
fact:
fact(4)
4! = 4 · 3 · 2 · 1 = 24
Math:
n: 4
Using iterative control:
Using recursion:
def fact_iter(n):
total, k = 1, 1
while k <= n:
total, k = total*k, k+1
return total
def fact(n):
if n == 1:
return 1
return n * fact(n-1)
n! =
n
�
�
1
if n = 1
n! =
n · (n − 1) otherwise
i
i=1
fact(n-1)
n: 3
fact(n-1)
n: 2
n, total, k
n: 1
n
fact(n):
...
6
if n == 1:
return 1
return n * fact(n-1)
2
if n == 1:
return 1
return n * fact(n-1)
fact(n-1)
Names:
24
if n == 1:
return 1
return n * fact(n-1)
1
if n == 1:
return 1
return n * fact(n-1)
def fact(n):
if n == 1:
return 1
return n * fact(n-1)
fact(4)
9
The Recursive Leap of Faith
10
Example: Reverse a String
def fact(n):
if n == 1:
return 1
return n * fact(n-1)
def reverse(s):
"""Return the reverse of a string s."""
Recursive idea: The reverse of a string is the reverse
of the rest of the string, followed by the first letter.
Is fact implemented correctly?
antidisestablishmentarianism
1. Verify the base case.
a ntidisestablishmentarianism
2. Treat fact(n-1) as a functional
abstraction!
msinairatnemhsilbatsesiditn a
3. Assume that fact(n-1) is correct.
reverse(s[1:]) + s[0]
4. Verify that fact(n) is correct,
assuming that fact(n-1) correct.
Base Case: The reverse of an empty string is itself.
Photo by Kevin Lee, Preikestolen, Norway
11
12
Converting Recursion to Iteration
Converting Iteration to Recursion
Hard! Iteration is a special case of recursion
More formulaic: Iteration is a special case of recursion
Idea: Figure out what state must be maintained by the function
Idea: The state of an iteration can be passed as parameters
def reverse_iter(s):
r, i = '', 0
while i < len(s):
r, i = s[i] + r, i + 1
return r
def reverse(s):
if s == '':
return s
return reverse(s[1:]) + s[0]
What's reversed
so far?
How to get each
incremental piece
Assignment becomes...
def reverse2(s):
def rev(s, r, i):
if not i < len(s):
return r
return rev(s, s[i] + r, i + 1)
return rev(s, '', 0)
def reverse_iter(s):
r, i = '', 0
while i < len(s):
r, i = s[i] + r, i + 1
return r
13
Arguments to a
recursive call
14
© Copyright 2026 Paperzz