Functional Python Programming

(Wang) #1
Chapter 4

Our strategy for performing tail-call optimization is to replace the recursion with a
generator expression. We can clearly optimize this recursion into a simple for loop.
The following is another version of a function to pair up the points along a route:


def legs(lat_lon_iter):


begin= next(lat_lon_iter)


for end in lat_lon_iter:


yield begin, end


begin= end


The version is quite fast and free from stack limits. It's independent of any
particular type of sequence, as it will pair up anything emitted by a sequence
generator. As there's no processing function inside loop, we can reuse the
legs() function as needed.


We can think of this function as one that yields the following kind of sequence
of pairs:


list[0:1], list[1:2], list[2:3], ..., list[-2:]


Another view of this function is as follows:


zip(list, list[1:])


While informative, these other two formulations only work for sequence objects.
The legs() and pairs() functions work for any iterable, including sequence objects.


Using the iter() function explicitly


The purely functional viewpoint is that all of our iterables can be processed with
recursive functions, where the state is merely the recursive call stack. Pragmatically,
Python iterables will often involve evaluation of other for loops. There are two
common situations: collections and iterables. When working with a collection,
an iterator object is created by the for statement. When working with a generator
function, the generator function is the iterator and maintains its own internal state.
Often, these are equivalent from a Python programming perspective. In rare cases,
generally those situations where we have to use an explicit next() function, the two
won't be precisely equivalent.


Our legs() function shown previously has an explicit next() function call to get the
first value from the iterable. This works wonderfully well with generator functions,
expressions, and other iterables. It doesn't work with sequence objects such as tuples
or lists.

Free download pdf