Tail-call optimization for collections

We have two general ways to handle collections: we can use a higher-order function that returns a generator expression, or we can create a function that uses a for loop to process each item in a collection. The two essential patterns are very similar.

Following is a higher-order function that behaves like the built-in map() function:

from typing import Callable, Iterable, Iterator, Any, TypeVarD_ = TypeVar("D_")R_ = TypeVar("R_")def mapf(        f: Callable[[D_], R_],         C: Iterable[D_]    ) -> Iterator[R_]:    return (f(x) for x in C)

We've returned a generator expression that produces the required mapping. This uses the explicit for in the generator expression as a kind of tail-call optimization. 

The source of data  ...

Get Functional Python Programming - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.