Functional Python Programming

(Wang) #1
Chapter 13

Once we have a prod() function, this means that the factorial can be defined
as follows:


fact= lambda n: 1 if n < 2 else n*prod(range(1,n))


This has the advantage of being succinct: it provides a single line definition of
factorial. It also has the advantage of not relying on recursion but has the potential
of running afoul Python's stack limit.


It's not clear that this has any dramatic advantages over the many alternatives we
have in Python. The concept of building a complex function from primitive pieces
like the partial() and reduce() functions, and the operator module is very
elegant. In most cases, though, the simple functions in the operator module aren't
very helpful; we'll almost always want to use more complex lambdas.


Summary


In this chapter, we looked at alternatives to the if, elif, and else statement
sequence. Ideally, using a conditional expression allows some optimization to be
done. Pragmatically, Python doesn't optimize, so there's little tangible benefit to the
more exotic ways to handle conditions.


We also looked at how we can use the operator module with higher order functions
like max(), min(), sorted(), and reduce(). Using operators can save us from
having to create a number of small lambdas.


In the next chapter, we'll look at the PyMonad library to express a functional
programming concept directly in Python. We don't require monads generally
because Python is an imperative programming language under the hood.


Some algorithms might be expressed more clearly with monads than with stateful
variable assignments. We'll look at an example where monads lead to a succinct
expression of a rather complex set of rules. Most importantly, the operator module
shows off many functional programming techniques.

Free download pdf