Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Lab 5: Closures and iterators

Objectives: LO-5.1, LO-5.2, LO-5.3
Prerequisites: the Module 5 reading and Lab 4
Time: about 2 hours

You will predict what closures return, write reduce and a compose that takes any number of functions, count the calls a recursive function makes before and after memoizing it, and write a stateful and a stateless iterator. As in the earlier labs, each exercise ends with a check cell that prints passed or fails with a message, and the checks fail until you finish their exercise.

Setup

Nothing in this lab is random. Section 3 measures time, so its numbers depend on your machine. The second cell prints the Lua version, which should be Lua 5.4.

1. What a closure sees

The next cell defines two factories from the reading as globals, so the snippets below can use them. Run it, then try a few calls of your own, such as local c = new_counter(); print(c(), c()).

Exercise L5.1 (LO-5.1, ★★, about 15 minutes)

Each snippet is a short program that ends by returning one value. Predict that value and replace its "?" with it: a number, or a string in quotes. Make all eight predictions before you run the check.

2. Functions that combine functions

Exercise L5.2 (LO-5.2, ★★, about 20 minutes)

Write two global functions:

  • reduce(list, fn, initial) combines the items of list from left to right: starting from initial, it replaces the running value acc with fn(acc, item) for each item, and returns the last acc. When initial is nil, it starts from the first item and combines the rest. With an empty list and no initial, it returns nil.

  • compose(...) takes any number of functions and returns one function that applies them from right to left, passing every result of one to the next: compose(f, g, h)(x) is f(g(h(x))). compose() returns a function that returns its arguments unchanged.

Hint

For compose, keep the functions with table.pack(...), and inside the new function keep the current values the same way, so that a nil among them isn’t lost. table.unpack(t, 1, t.n) gives them back.

3. Counting calls, then memoizing

slow_fib adds one to the global fib_calls each time it is called. The cell after it computes three Fibonacci numbers and prints how many calls each took. Before you run it, predict: when n grows by 5, how many times more calls does slow_fib(n) make? The cell takes under a second.

Each 5 more multiplies the calls by about 11, because the number of calls grows like the Fibonacci numbers themselves, by a factor of about 1.618 for each 1 added to n.

Exercise L5.3 (LO-5.2, ★★★, about 25 minutes)

  1. Write memoize(fn) for a function fn of one argument, which is never nil. It returns a new function that calls fn at most once for each argument, and returns the cached result on every later call, including when the result is nil or false.

  2. Set the global memo_fib to a memoized Fibonacci function whose inner function adds one to fib_calls on every call, as slow_fib does, and whose recursive calls go through the cache.

Hint 1

The reading’s memoize tests cache[n] == nil, which can’t tell “not computed yet” from “computed, and the result was nil”. Store a placeholder in the cache in place of nil: a new empty table, created once outside the returned function, is equal to nothing else.

Hint 2

Inside the inner function, call memo_fib, not slow_fib. The global memo_fib is looked up when the call happens, after you have assigned it.

4. A stateful iterator

Exercise L5.4 (LO-5.3, ★★, about 20 minutes)

Write range(from, to, step), which returns an iterator that the generic for can use to visit the same integers as the numeric for i = from, to, step. step defaults to 1, all three arguments are integers, and a step of 0 raises an error. Once the iterator has returned nil, it keeps returning nil.

LoopVisits
for v in range(1, 10, 3)1, 4, 7, 10
for v in range(5, 1, -2)5, 3, 1
for v in range(3, 3)3
for v in range(1, 0)nothing
Hint

Keep the next value in a local of range, and return a closure that tests it against to, which way depending on the sign of step.

5. A stateless iterator

Exercise L5.5 (LO-5.3, ★★, about 20 minutes)

Write reverse_ipairs(list), which visits a sequence from its last item to its first: for i, v in reverse_ipairs({ "a", "b", "c" }) visits 3, "c", then 2, "b", then 1, "a". Make it stateless, like the reading’s my_ipairs: it returns one step function defined once, outside reverse_ipairs; the list as the state; and #list + 1 as the first control value, which is the index of the item visited last. Then answer the question in the Markdown cell after the check.

Your answer here: why can every loop share reverse_ipairs’s step function, while every loop needs a new closure from range?

Summary

  • A closure captures variables, not values, and closures made in one call share them; for loops give each pass a new variable, and while loops don’t.

  • reduce and compose are ordinary functions that take functions, and table.pack keeps every value, nil included, when a function passes them along.

  • Naive fib(n) makes about 11 times more calls for each 5 added to n; memoized, with the recursion going through the cache, it makes n + 1.

  • Caching nil and false needs a placeholder value, because a table can’t store nil.

  • A stateful iterator keeps its position in a closure and is used up after one loop; a stateless one keeps it in the control value, and one step function serves every loop.

Next, do the Module 5 practice.