Skip to Content
Functional Python Programming - Second Edition
book

Functional Python Programming - Second Edition

by Steven F. Lott
April 2018
Intermediate to advanced content levelIntermediate to advanced
408 pages
10h 42m
English
Packt Publishing
Content preview from Functional Python Programming - Second Edition

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  ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Functional Python Programming - Third Edition

Functional Python Programming - Third Edition

Steven F. Lott

Publisher Resources

ISBN: 9781788627061Supplemental Content