Other Ways to open this chapter: JupyterLite | Colab | Read Only | Download

Ignore this cell — used when running JupyterLite.

from os.path import basename, exists

def download(url):
    """Download a file if it isn't already here, and return its filename."""
    filename = basename(url)
    if not exists(filename):
        from urllib.request import urlretrieve

        local, _ = urlretrieve(url, filename)
        print("Downloaded " + str(local))
    return filename

download('https://github.com/porttack/working-in-python/raw/v3/working_in_python.py');
download('https://github.com/AllenDowney/ThinkPython/raw/v3/diagram.py');

import working_in_python

6. Return Values#

In previous chapters, we’ve used built-in functions – like abs and round – and functions in the math module – like sqrt and pow. When you call one of these functions, it returns a value you can assign to a variable or use as part of an expression.

The functions we have written so far are different. Some use the print function to display values, and some use turtle functions to draw figures. But they don’t return values we assign to variables or use in expressions.

In this chapter, we’ll see how to write functions that return values.

6.1. Some functions have return values#

When you call a function like math.sqrt, the result is called a return value. If the function call appears at the end of a cell, Jupyter displays the return value immediately.

import math

math.sqrt(42 / math.pi)

If you assign the return value to a variable, it doesn’t get displayed.

radius = math.sqrt(42 / math.pi)

But you can display it later.

radius

Or you can use the return value as part of an expression.

radius + math.sqrt(42 / math.pi)

Here’s an example of a function that returns a value.

def circle_area(radius):
    area = math.pi * radius**2
    return area

circle_area takes radius as a parameter and computes the area of a circle with that radius.

The last line is a return statement that returns the value of area.

If we call the function like this, Jupyter displays the return value.

circle_area(radius)

We can assign the return value to a variable.

a = circle_area(radius)

Or use it as part of an expression.

circle_area(radius) + 2 * circle_area(radius / 2)

Later we can display the value of the variable we assigned the result to.

a

But we can’t access area.

area

area is a local variable in a function, so we can’t access it from outside the function.

6.2. And some have None#

If a function doesn’t have a return statement, it returns None, which is a special value like True and False. For example, here’s the repeat function from Chapter 3.

def repeat(word, n):
    print(word * n)

If we call it like this, it displays the first line of the Monty Python song “Finland”.

repeat('Finland, ', 3)

This function uses the print function to display a string, but it does not use a return statement to return a value. If we assign the result to a variable, it displays the string anyway.

result = repeat('Finland, ', 3)

And if we display the value of the variable, we get nothing.

result

result actually has a value, but Jupyter doesn’t show it. However, we can display it like this.

print(result)

The return value from repeat is None.

Now here’s a function similar to repeat except that has a return value.

def repeat_string(word, n):
    return word * n

Notice that we can use an expression in a return statement, not just a variable.

With this version, we can assign the result to a variable. When the function runs, it doesn’t display anything.

line = repeat_string('Spam, ', 4)

But later we can display the value assigned to line.

line

A function like this is called a pure function because it returns a value and has no side effects.

6.3. Return values and conditionals#

If Python did not provide abs, we could write it like this.

def absolute_value(x):
    if x < 0:
        return -x
    else:
        return x

If x is negative, the first return statement returns -x and the function ends immediately. Otherwise, the second return statement returns x and the function ends. So this function is correct.

However, if you put return statements in a conditional, you have to make sure that every possible path through the program hits a return statement. For example, here’s an incorrect version of absolute_value.

def absolute_value_wrong(x):
    if x < 0:
        return -x
    if x > 0:
        return x

Here’s what happens if we call this function with 0 as an argument.

absolute_value_wrong(0)

We get nothing! Here’s the problem: when x is 0, neither condition is true, and the function ends without hitting a return statement, which means that the return value is None, so Jupyter displays nothing.

As another example, here’s a version of absolute_value with an extra return statement at the end.

def absolute_value_extra_return(x):
    if x < 0:
        return -x
    else:
        return x
    
    return 'This is dead code'

If x is negative, the first return statement runs and the function ends. Otherwise the second return statement runs and the function ends. Either way, we never get to the third return statement – so it can never run.

Code that can never run is called dead code. In general, dead code doesn’t do any harm, but it often indicates a misunderstanding, and it might be confusing to someone trying to understand the program.

6.4. Incremental development#

As you write larger functions, you might find yourself spending more time debugging. To deal with increasingly complex programs, you might want to try incremental development, which is a way of adding and testing only a small amount of code at a time.

As an example, suppose you want to find the distance between two points represented by the coordinates \((x_1, y_1)\) and \((x_2, y_2)\). By the Pythagorean theorem, the distance is:

\[\mathrm{distance} = \sqrt{(x_2 - x_1)^2 + (y_2 - y_1)^2}\]

The first step is to consider what a distance function should look like in Python – that is, what are the inputs (parameters) and what is the output (return value)?

For this function, the inputs are the coordinates of the points. The return value is the distance. Immediately you can write an outline of the function:

def distance(x1, y1, x2, y2):
    return 0.0

This version doesn’t compute distances yet – it always returns zero. But it is a complete function with a return value, which means that you can test it before you make it more complicated.

To test the new function, we’ll call it with sample arguments:

distance(1, 2, 4, 6)

I chose these values so that the horizontal distance is 3 and the vertical distance is 4. That way, the result is 5, the hypotenuse of a 3-4-5 right triangle. When testing a function, it is useful to know the right answer.

At this point we have confirmed that the function runs and returns a value, and we can start adding code to the body. A good next step is to find the differences x2 - x1 and y2 - y1. Here’s a version that stores those values in temporary variables and displays them.

def distance(x1, y1, x2, y2):
    dx = x2 - x1
    dy = y2 - y1
    print('dx is', dx)
    print('dy is', dy)
    return 0.0

If the function is working, it should display dx is 3 and dy is 4. If so, we know that the function is getting the right arguments and performing the first computation correctly. If not, there are only a few lines to check.

distance(1, 2, 4, 6)

Good so far. Next we compute the sum of squares of dx and dy:

def distance(x1, y1, x2, y2):
    dx = x2 - x1
    dy = y2 - y1
    dsquared = dx**2 + dy**2
    print('dsquared is: ', dsquared)
    return 0.0

Again, we can run the function and check the output, which should be 25.

distance(1, 2, 4, 6)

Finally, we can use math.sqrt to compute the distance:

def distance(x1, y1, x2, y2):
    dx = x2 - x1
    dy = y2 - y1
    dsquared = dx**2 + dy**2
    result = math.sqrt(dsquared)
    print("result is", result)

And test it.

distance(1, 2, 4, 6)

The result is correct, but this version of the function displays the result rather than returning it, so the return value is None.

We can fix that by replacing the print function with a return statement.

def distance(x1, y1, x2, y2):
    dx = x2 - x1
    dy = y2 - y1
    dsquared = dx**2 + dy**2
    result = math.sqrt(dsquared)
    return result

This version of distance is a pure function. If we call it like this, only the result is displayed.

distance(1, 2, 4, 6)

And if we assign the result to a variable, nothing is displayed.

d = distance(1, 2, 4, 6)

The print statements we wrote are useful for debugging, but once the function is working, we can remove them. Code like that is called scaffolding because it is helpful for building the program but is not part of the final product.

This example demonstrates incremental development. The key aspects of this process are:

  1. Start with a working program, make small changes, and test after every change.

  2. Use variables to hold intermediate values so you can display and check them.

  3. Once the program is working, remove the scaffolding.

At any point, if there is an error, you should have a good idea where it is. Incremental development can save you a lot of debugging time.

6.5. Boolean functions#

Functions can return the boolean values True and False, which is often convenient for encapsulating a complex test in a function. For example, is_divisible checks whether x is divisible by y with no remainder.

def is_divisible(x, y):
    if x % y == 0:
        return True
    else:
        return False

Here’s how we use it.

is_divisible(6, 4)
is_divisible(6, 3)

Inside the function, the result of the == operator is a boolean, so we can write the function more concisely by returning it directly.

def is_divisible(x, y):
    return x % y == 0

Boolean functions are often used in conditional statements.

if is_divisible(6, 2):
    print('divisible')

It might be tempting to write something like this:

if is_divisible(6, 2) == True:
    print('divisible')

But the comparison is unnecessary.

6.6. Recursion with return values#

Now that we can write functions with return values, we can write recursive functions with return values, and with that capability, we have passed an important threshold – the subset of Python we have is now Turing complete, which means that we can perform any computation that can be described by an algorithm.

To demonstrate recursion with return values, we’ll evaluate a few recursively defined mathematical functions. A recursive definition is similar to a circular definition, in the sense that the definition refers to the thing being defined. A truly circular definition is not very useful:

vorpal: An adjective used to describe something that is vorpal.

If you saw that definition in the dictionary, you might be annoyed. On the other hand, if you looked up the definition of the factorial function, denoted with the symbol \(!\), you might get something like this:

\[\begin{split}\begin{aligned} 0! &= 1 \\ n! &= n~(n-1)! \end{aligned}\end{split}\]

This definition says that the factorial of \(0\) is \(1\), and the factorial of any other value, \(n\), is \(n\) multiplied by the factorial of \(n-1\).

If you can write a recursive definition of something, you can write a Python program to evaluate it. Following an incremental development process, we’ll start with a function that take n as a parameter and always returns 0.

def factorial(n):
    return 0

Now let’s add the first part of the definition – if the argument happens to be 0, all we have to do is return 1:

def factorial(n):
    if n == 0:
        return 1
    else:
        return 0

Now let’s fill in the second part – if n is not 0, we have to make a recursive call to find the factorial of n-1 and then multiply the result by n:

def factorial(n):
    if n == 0:
        return 1
    else:
        recurse = factorial(n-1)
        return n * recurse

The flow of execution for this program is similar to the flow of countdown in Chapter 5. If we call factorial with the value 3:

Since 3 is not 0, we take the second branch and calculate the factorial of n-1.…

Since 2 is not 0, we take the second branch and calculate the factorial of n-1.…

Since 1 is not 0, we take the second branch and calculate the factorial of n-1.…

Since 0 equals 0, we take the first branch and return 1 without making any more recursive calls.

The return value, 1, is multiplied by n, which is 1, and the result is returned.

The return value, 1, is multiplied by n, which is 2, and the result is returned.

The return value 2 is multiplied by n, which is 3, and the result, 6, becomes the return value of the function call that started the whole process.

The following figure shows the stack diagram for this sequence of function calls.

from diagram import Frame, Stack, make_binding

main = Frame([], name='__main__', loc='left')
frames = [main]

ns = 3, 2, 1
recurses = 2, 1, 1
results = 6, 2, 1

for n, recurse, result in zip(ns, recurses, results):
    binding1 = make_binding('n', n)
    binding2 = make_binding('recurse', recurse)
    frame = Frame([binding1, binding2], 
                  name='factorial', value=result,
                  loc='left', dx=1.2)
    frames.append(frame)
    
binding1 = make_binding('n', 0)
frame = Frame([binding1], name='factorial', value=1, 
              shim=1.2, loc='left', dx=1.4)
frames.append(frame)

stack = Stack(frames, dy=-0.45)
from diagram import diagram, adjust

width, height, x, y = [2.74, 2.26, 0.73, 2.05]
ax = diagram(width, height)
bbox = stack.draw(ax, x, y)
# adjust(x, y, bbox)

The return values are shown being passed back up the stack. In each frame, the return value is the product of n and recurse.

In the last frame, the local variable recurse does not exist because the branch that creates it does not run.

6.7. Leap of faith#

Following the flow of execution is one way to read programs, but it can quickly become overwhelming. An alternative is what I call the “leap of faith”. When you come to a function call, instead of following the flow of execution, you assume that the function works correctly and returns the right result.

In fact, you are already practicing this leap of faith when you use built-in functions. When you call abs or math.sqrt, you don’t examine the bodies of those functions – you just assume that they work.

The same is true when you call one of your own functions. For example, earlier we wrote a function called is_divisible that determines whether one number is divisible by another. Once we convince ourselves that this function is correct, we can use it without looking at the body again.

The same is true of recursive programs. When you get to the recursive call, instead of following the flow of execution, you should assume that the recursive call works and then ask yourself, “Assuming that I can compute the factorial of \(n-1\), can I compute the factorial of \(n\)?” The recursive definition of factorial implies that you can, by multiplying by \(n\).

Of course, it’s a bit strange to assume that the function works correctly when you haven’t finished writing it, but that’s why it’s called a leap of faith!

6.8. Fibonacci#

After factorial, the most common example of a recursive function is fibonacci, which has the following definition:

\[\begin{split}\begin{aligned} \mathrm{fibonacci}(0) &= 0 \\ \mathrm{fibonacci}(1) &= 1 \\ \mathrm{fibonacci}(n) &= \mathrm{fibonacci}(n-1) + \mathrm{fibonacci}(n-2) \end{aligned}\end{split}\]

Translated into Python, it looks like this:

def fibonacci(n):
    if n == 0:
        return 0
    elif  n == 1:
        return 1
    else:
        return fibonacci(n-1) + fibonacci(n-2)

If you try to follow the flow of execution here, even for small values of \(n\), your head explodes. But according to the leap of faith, if you assume that the two recursive calls work correctly, you can be confident that the last return statement is correct.

As an aside, this way of computing Fibonacci numbers is very inefficient. In Chapter 10 I’ll explain why and suggest a way to improve it.

6.9. Checking types#

What happens if we call factorial and give it 1.5 as an argument?

factorial(1.5)

It looks like an infinite recursion. How can that be? The function has base cases when n == 1 or n == 0. But if n is not an integer, we can miss the base case and recurse forever.

In this example, the initial value of n is 1.5. In the first recursive call, the value of n is 0.5. In the next, it is -0.5. From there, it gets smaller (more negative), but it will never be 0.

To avoid infinite recursion we can use the built-in function isinstance to check the type of the argument. Here’s how we check whether a value is an integer.

isinstance(3, int)
isinstance(1.5, int)

Now here’s a version of factorial with error-checking.

def factorial(n):
    if not isinstance(n, int):
        print('factorial is only defined for integers.')
        return None
    elif n < 0:
        print('factorial is not defined for negative numbers.')
        return None
    elif n == 0:
        return 1
    else:
        return n * factorial(n-1)

First it checks whether n is an integer. If not, it displays an error message and returns None.

factorial('crunchy frog')

Then it checks whether n is negative. If so, it displays an error message and returns None.

factorial(-2)

If we get past both checks, we know that n is a non-negative integer, so we can be confident the recursion will terminate. Checking the parameters of a function to make sure they have the correct types and values is called input validation.

6.10. Debugging#

Breaking a large program into smaller functions creates natural checkpoints for debugging. If a function is not working, there are three possibilities to consider:

  • There is something wrong with the arguments the function is getting – that is, a precondition is violated.

  • There is something wrong with the function – that is, a postcondition is violated.

  • The caller is doing something wrong with the return value.

To rule out the first possibility, you can add a print statement at the beginning of the function that displays the values of the parameters (and maybe their types). Or you can write code that checks the preconditions explicitly.

If the parameters look good, you can add a print statement before each return statement and display the return value. If possible, call the function with arguments that make it easy check the result.

If the function seems to be working, look at the function call to make sure the return value is being used correctly – or used at all!

Adding print statements at the beginning and end of a function can help make the flow of execution more visible. For example, here is a version of factorial with print statements:

def factorial(n):
    space = ' ' * (4 * n)
    print(space, 'factorial', n)
    if n == 0:
        print(space, 'returning 1')
        return 1
    else:
        recurse = factorial(n-1)
        result = n * recurse
        print(space, 'returning', result)
        return result

space is a string of space characters that controls the indentation of the output. Here is the result of factorial(3) :

factorial(3)

If you are confused about the flow of execution, this kind of output can be helpful. It takes some time to develop effective scaffolding, but a little bit of scaffolding can save a lot of debugging.

6.11. Glossary#

return value: The result of a function. If a function call is used as an expression, the return value is the value of the expression.

side effect: Any effect a function has other than returning a value, such as displaying output or drawing on a canvas.

pure function: A function that returns a value and has no side effects.

dead code: Part of a program that can never run, often because it appears after a return statement.

incremental development: A program development plan intended to avoid debugging by adding and testing only a small amount of code at a time.

scaffolding: Code that is used during program development but is not part of the final version.

Turing complete: A language, or subset of a language, is Turing complete if it can perform any computation that can be described by an algorithm.

input validation: Checking the parameters of a function to make sure they have the correct types and values

See also: the full vocabulary glossary collects every term in this book, alphabetized, alongside the complete AP CSP exam vocabulary list.

6.12. Exercises#

# This cell tells Jupyter to provide detailed debugging information
# when a runtime error occurs. Run it before working on the exercises.

%xmode Verbose

6.12.1. Exercise#

Use incremental development to write a function called hypot that returns the length of the hypotenuse of a right triangle given the lengths of the other two legs as arguments.

Note: There’s a function in the math module called hypot that does the same thing, but you should not use it for this exercise!

Even if you can write the function correctly on the first try, start with a function that always returns 0 and practice making small changes, testing as you go. When you are done, the function should only return a value – it should not display anything.

6.12.2. Exercise#

Write a boolean function, is_between(x, y, z), that returns True if \(x < y < z\) or if \(z < y < x\), andFalse otherwise.

You can use these examples to test your function.

is_between(1, 2, 3)  # should be True
is_between(3, 2, 1)  # should be True
is_between(1, 3, 2)  # should be False
is_between(2, 3, 1)  # should be False

6.12.3. Exercise#

The Ackermann function, \(A(m, n)\), is defined:

\[\begin{split}\begin{aligned} A(m, n) = \begin{cases} n+1 & \mbox{if } m = 0 \\ A(m-1, 1) & \mbox{if } m > 0 \mbox{ and } n = 0 \\ A(m-1, A(m, n-1)) & \mbox{if } m > 0 \mbox{ and } n > 0. \end{cases} \end{aligned}\end{split}\]

Write a function named ackermann that evaluates the Ackermann function. What happens if you call ackermann(5, 5)?

You can use these examples to test your function.

ackermann(3, 2)  # should be 29
ackermann(3, 3)  # should be 61
ackermann(3, 4)  # should be 125

If you call this function with values bigger than 4, you get a RecursionError.

ackermann(5, 5)

To see why, add a print statement to the beginning of the function to display the values of the parameters, and then run the examples again.

6.12.4. Exercise#

A number, \(a\), is a power of \(b\) if it is divisible by \(b\) and \(a/b\) is a power of \(b\). Write a function called is_power that takes parameters a and b and returns True if a is a power of b. Note: you will have to think about the base case.

You can use these examples to test your function.

is_power(65536, 2)   # should be True
is_power(27, 3)  # should be True
is_power(24, 2)  # should be False
is_power(1, 17)   # should be True

6.12.5. Exercise#

The greatest common divisor (GCD) of \(a\) and \(b\) is the largest number that divides both of them with no remainder.

One way to find the GCD of two numbers is based on the observation that if \(r\) is the remainder when \(a\) is divided by \(b\), then \(gcd(a, b) = gcd(b, r)\). As a base case, we can use \(gcd(a, 0) = a\).

Write a function called gcd that takes parameters a and b and returns their greatest common divisor.

You can use these examples to test your function.

gcd(12, 8)    # should be 4
gcd(13, 17)   # should be 1

6.13. Homework#

Required work is four exercises: whichever of Exercise 1 or Exercise 2, plus Exercises 3-5, about 31 minutes total. Doing both 1 and 2 is fine, but the second one earns no additional credit. The time check below must be filled in. The extra credit at the end (to_binary and collatz_steps) is the only extra credit in this chapter. It’s optional and never substitutes for a required exercise.

Every function you write in this section needs a docstring, the same as chapter 4 on.

Note: the exercises above (hypot, is_between, the Ackermann function, is_power, and gcd) are practice. They aren’t graded. This is the graded homework.

6.13.1. Exercise 1: is_right_triangle (do 1 or 2)#

Write a function called is_right_triangle that takes three side lengths, a, b, and c, and returns True if they form a right triangle (the Pythagorean theorem holds for some pairing of the three sides as the two legs and the hypotenuse) and False otherwise. Don’t assume the sides are given in any particular order.

Test your function with the following cases.

if is_right_triangle(3, 4, 5):
    print('right triangle')
is_right_triangle(4, 5, 3)   # should be True
is_right_triangle(2, 3, 4)   # should be False
is_right_triangle(0, 5, 5)   # should be True

6.13.2. Exercise 2: can_ride (do 1 or 2)#

Write a function called can_ride that takes height_inches and age and returns True if the person may ride: at least 48 inches tall, or at least 42 inches tall and at least 8 years old. Otherwise it returns False.

Test your function with the following cases.

if can_ride(50, 5):
    print('can ride')
can_ride(44, 6)   # should be False
can_ride(40, 10)   # should be False
can_ride(36, 5)   # should be False

6.13.3. Exercise 3: sum_to#

Write a recursive function called sum_to that takes a positive integer n and returns the sum of the integers from 1 to n. As a base case, sum_to(0) should return 0.

Test your function with the following cases.

sum_to(0)    # should be 0
sum_to(1)    # should be 1
sum_to(5)    # should be 15
sum_to(10)   # should be 55

6.13.4. Exercise 4: debug grade_points#

Here’s a function that’s supposed to convert a letter grade into grade points.

def grade_points(letter):
    if letter == 'A':
        print(4.0)
    elif letter == 'B':
        print(3.0)
    elif letter == 'C':
        print(2.0)

Predict what gpa will be before you run the cell below.

%xmode Context
gpa = grade_points('A') * 3

In the markdown cell below, explain what goes wrong and why. Then, in the code cell after that, write a corrected version of grade_points and test it with 'A', 'B', and 'C'.

Type your answer here.

6.13.5. Exercise 5: reflection#

This chapter’s functions return values instead of printing them. Give one example from your own code (from this chapter or an earlier one) where returning a value would let you do something that printing would not.

Answer in the markdown cell below, the same way you did in chap01 through chap05.

Type your answer here.

6.13.6. Time check#

This is graded on being filled in, not on the numbers. There’s no right answer, and low numbers don’t score better. If this chapter took you three hours, I need to know that. These are estimates: nobody expects you to have timed yourself, so a rough number is exactly what’s wanted.

# Fill this in before you submit. Rough estimates are fine, and low numbers
# don't score better. Don't count time on the extra credit below.
# chapter_minutes -> reading the chapter and its practice exercises
# extra_exercises_minutes -> the five numbered exercises above
# longest -> which exercise took longest, e.g. 1
chapter_minutes = 0
extra_exercises_minutes = 0
longest = 0

from working_in_python import time_check
time_check(chapter_minutes, extra_exercises_minutes, longest)

6.14. Extra credit: to_binary and collatz_steps#

Both of these are worth 0.25 points each, for 0.5 points total. Do one or both. Either is open to you once you’ve finished the five required exercises above; neither substitutes for any of them.

6.14.1. to_binary (extra credit)#

Write a recursive function called to_binary that takes a non-negative integer n and returns its binary representation as a string of ones and zeros. This is how a number actually lives in memory, one bit at a time.

Test your function with the following cases.

to_binary(0)    # should be '0'
to_binary(1)    # should be '1'
to_binary(10)   # should be '1010'

6.14.2. collatz_steps (extra credit)#

Write a recursive function called collatz_steps that takes a positive integer n and returns the number of steps it takes to reach 1 under the Collatz process: if n is even, the next number is n // 2; if n is odd, the next number is 3 * n + 1. collatz_steps(1) should return 0.

Test your function with the following cases.

collatz_steps(1)   # should be 0
collatz_steps(6)   # should be 8

6.14.3. Finished? Copy your work#

This isn’t part of Exercise 5. It’s a tool. Run the cell below to copy this notebook (including anything you’ve run) so you can paste it into a document.

working_in_python.show_copy_notebook_button()

Working in Python — modified by Eric Brown for a high school Computer Science Principles class. Source and modifications: github.com/porttack/working-in-python


Think Python: 3rd Edition

Copyright 2024 Allen B. Downey

Code license: MIT License

Text license: Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International


6.15. Standards alignment#

AP CSP: 3.9 Developing Algorithms and 3.12 Calling Procedures (Big Idea 3, 30–35% of the exam). Also 1.4 Identifying and Correcting Errors (Big Idea 1, 10–13%), headers only. California 9-12: 9-12.AP.14 CSTA 2026: HS-PRO-RD-17, headers only — no CSTA HS standard names recursion or abstraction directly. CA CTE (ICT): C4.9 (Pathway C) and 5.10 (Anchor Standard 5, Problem Solving). Also C4.4 and C5.6, headers only.

Return values let a function call nest inside an expression, which is 3.9 and 3.12 built out with five successive versions of distance. factorial and fibonacci calling themselves is exactly CTE’s “function that calls itself,” completing the same construct California’s AP.14 asks for — thin on the iterative side, since this book has no while loop to compare recursion against. The leap of faith, trusting a function’s return value without re-checking its body, is this book’s clearest statement yet of CTE’s layers-of-abstraction standard.