Higher-Order Functions, Self Reference 15
(0, 0) as arguments to g is a sure indicator to h that we are currently on the rst
number of a chain, and we should not print anything (otherwise, when else would
you see a 0 passed in as x?).
The second case is trickier. First, we need to print a number if our expected number
diers from the observed number, but we also need to update expected_num and
count since the chain is going to restart when the chain breaks. To do this in
one line, we appeal to lab01, in which we learned that the return value of print is
None, which is false-y, and that or operators short-circuit only if a truth-y value is
encountered before the last operand. We can print x which is our expected number
along with the number of chain breaks y + 1. This whole procedure returns None,
so if we stick it as the rst operand of the or operator, we know that the or operator
will not short-circuit. The program will then proceed to evaluate g(n + 1, y +
1), which returns h. Although not necessary for this problem, it may be helpful
to know that a function is truth-y. In this case, it doesn’t matter because an or
will return the last operand it is given if it doesn’t short-circuit, regardless of the
truth-y-ness of the last operand. Hence, the last line of h prints the appropriate
numbers, updates the expected_num (restarting the chain), updates the count, and
returns h, which will accept the next natural number into the chain.Why does g
return h? Watch the indentations of each line very closely. The only thing the g
function does is dene a function h and then return h. All that other stu where
we check for equality and return print etc is all inside the h function. Hence, that
code is not executed until we call h.
As a side note, if you are stuck on a problem like this one on an exam, it may
be helpful to ignore the skeleton and rst implement the code assuming you have
unlimited lines and freedom to name your variables whatever you want. When I
was writing this question, I named all my functions something meaningful, and you
bet that my variables were not x and y but expected_num and count. I also had a
separate line for the print. However, once I got into making a template skeleton for
an exam level problem, I thought “how do I obfuscate the code to force people to
think harder?” The variable name changes were easy, and condensing the print into
the same line as the return was just a trick I’ve seen from previous exams in this
course. I think that coming up with the whole solution from scratch by following the
template is immensely harder than rst coming up with your own working solution
and then massaging your solution into the constraints of our blank lines.
• Derek Wan, Fall 2020
Note: This worksheet is a problem bank—most TAs will not cover all the problems in discussion section.