# Anonymous Memoizing Lazy Lists

A vastly prettier version of this blog can be found in the CDF file here: https://dl.dropbox.com/u/1997638/LazyLambda003.cdf. Wolfram’s free CDF reader is found at http://www.wolfram.com/cdf-player/.

One reason to care about anonymized computations is that naming things costs memory, and it’s the kind of memory that lasts from one computation to another – session memory. Naming things means writing definitions and storing them in tables for access in later computations. Building up big memoization tables as definitions can cost a LOT of memory. We can save this cost if we can avoid naming things, storing information in function parameters that only last the lifetime of a single computation.

## NON-ANONYMOUS LAZY LISTS

Lazy lists are a handy way of expressing infinite data streams. A typical lazy list might look like the following:

Calling integersFrom with some numerical argument produces a list in curly braces, the first element of which is that numerical argument and the second element of which is a delayed list in the form of a nullary function – a function of no parameters. That’s what the & means: “the expression to my left is a function.” We’re doing Lisp-style lists, which are pairs of values and lists.

The list in the second slot of the lazy list won’t be automatically evaluated – we must manually invoke the function that produces it when we want the results. That is the essence of lazy computation. Lazy languages like Haskell can decide when you need the results and just sidestep the explicit wrapping in a nullary function and the manual invocation. With eager or strict languages like Mathematica, we must do the invocations manually. But that’s good, because we can see more clearly what’s going on.

In our lazy lists, the second item will always be a nullary function.

Start peeling integers off such a structure one at a time. integersFrom[0] will be a lazy list of integers starting from 0, and [[1]] will pick the first element from the resulting list:

If we pick the second element from integersFrom[0], that will be a nullary function that produces the next lazy list. Manually invoke the function by appending [] – invocation brackets containing no arguments – and then pick off the first element of the result to get the next integer.

And so on:

A pattern emerges that we can capture in some operators. Value just picks the first element of a lazy list, and next picks the second element – the nullary function – and invokes it on no arguments:

Improve the value operator so we can ask for the n th value, recursively:

Let’s see a few values by mapping over a list of inputs:

We don’t need next any more – only value used it. Inline it in the body of value:

As an aside, an efficient implementation of value requires either the tail-recursion optimization in the interpreter or a re-expression in iterative form, which can be done semi-automatically.

Write another lazy list as follows:

Of course, this is exponentially inefficient, as are all non-memoizing recursive fibonaccis. Fib of 15 is already painful, and fib of 150 is unthinkable. This can be mitigated as follows:

This is a well-known Mathematica idiom for building a memo table by side effect. The memo table consists of explicit, specific point-values for fibonaccis, which the general fibonaccis – the one depending on a single parameter n_ – creates on-the-fly. Subsequent references to fibonaccis at known inputs will do a quick lookup on the specific values and avoid the exponential recomputation.

This is non-anonymous programming on steroids – everything is built up inside the named object fibonaccis, but it gives us great speed at the expense of memory. But this is global memory in Mathematica’s global brain. When we’re done with the calculation, we have modified the session state of Mathematica and not left things the way we found them. In some scenarios, this would not be allowed. We must find some other way to evaluate recursive formulas without requiring session state – using only ephemeral memory such as stack frames that go away when our result is achieved.

Let’s get rid of the named functions and then even get rid of the named memo table so we can have decent performance on our recursive evaluations.

## ANONYMIZE

The mother of all anonymizers is the Y combinator:

Without going into how it works, Y is a function that takes another function as an argument. That other function takes an argument k and produces a function of n. The function of n can call k as if k were a recursive definition of the function of n. The function of n can be applied to workhorse arguments, that is, to arguments of the subject code.

In practice, Y is easy to use: just apply it to a function of k that produces a function of n that internally calls k, then apply the result to the desired n.

Here is the lazy list of integers, this time starting at 1, without using the name of the lazy list inside the definition of the lazy list: s1 does not refer to s1:

We feed to Y a function of k. That function of k produces a function of n. That function of n produces a list in curly braces. The first element of that list is the value n, and the second element of that list is a delayed call of k on the next value, n+1. s1 is thus a lazy list of all the integers, just defined without reference to any names but parameters. No global storage needed, no session state.

Let’s map calls of value[s1,#]& over a sequence of inputs to consicely show it off multiple times:

Now, on to an anonymized lazy list of fibonaccis:

This one is still slow:

It takes about a second to produce fib[20], and higher values become intolerable. We would never get to an absurd input like 150.

## MEMOIZE

How can we speed it up without defining point values in some named object? By defining point values in an un-named object, of course! Un-named objects are best modeled in Mathematica as lists of rules, one for each point-like input. We’ll need to pass that around in the argument list of k, and the easiest way to do that is to make n, the argument of k, a regular Mathematica list to contain both a value and an anonymous dictionary.

We’ll get to this form in a few steps. First, just change n so that it’s a list rather than an integer. This change spreads a lot of indexing around the body of k, so we want to make sure we get that right before proceeding:

Now add a second element – an empty list – to n, but ignore it in the code, just to make sure we get all the shaping correct. We must modify six places where arguments to k are constructed:

Now replace the internal constant empty lists with references to the second slot of n, where we will eventually store the dictionary:

We’re now ready to promote that second part of n into a dictionary – same as anonymous object, same as list of rules – for fast lookups. Let’s take the convention that if a key is not present in the dictionary, we produce Null, and make a few helper functions:

Add converts the dictionary into a hash table by applying the Mathematica built-in Dispatch to it. This is similar to what relational databases do when computing joins – creates a temporary hash table and uses it. Before adding a new rule to the table, add must check whether the input table is already a hash table since the original list of rules is stored in slot 1 of a hash table. Add can only add a rule to a list of rules, not to a hash table, but add can regenerate a new hash table in linear time. This is a potential hidden quadratic in this code since the hash table will be created over and over again. It does not seem to be a serious problem, here, likely overwhelmed by other overheads.

Now add the code to store computed values in the anonymous object. We must modify the initial input from {1, {}} to {1, {_->Null}} so that the starting dictionary has the default rule.

Now add code to do lookups

Now our regular example is much faster and an otherwise inconceivable computation such as fib[150] can be done in a reasonable time.

## CONCLUSION

Many improvements can be made to this, such as getting rid of the mutable variables in the Module` by a monadic bind and refactoring the code for readability. However, we have shown a general technique for creating lazy memoizing lists without introducing names or session state into an evaluator or interpreter.