Functional Python Programming

(Wang) #1
Chapter 14

Since a List object is a functor, we can map functions to the List object.
The function is applied to each item in the List object. Here's an example:





fact= prod range1n
seq1 = List(
range(20))
f1 = fact * seq1
f1[:10]
[1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880]





We defined a composite function, fact(), which was built from the prod() and
range1n() functions shown previously. This is the factorial function, n!. We created
a List() functor, seq1, which is a sequence of 20 values. We mapped the fact()
function to the seq1 functor, which created a sequence of factorial values, f1. We
showed the first 10 of these values earlier.


There is a similarity between the composition of functions and the
composition of a function and a functor. Both prod*range1n and
fact*seq1 use functional composition: one combines things that are
obviously functions, and the other combines a function and a functor.

Here's another little function that we'll use to extend this example:


@curry


def n21(n):


return 2*n+1


This little n21() function does a simple computation. It's curried, however,
so we can apply it to a functor like a List() function. Here's the next part of the
preceding example:





semi_fact= prod * alt_range








f2 = semi_fact n21 seq1








f2[:10]





[1, 3, 15, 105, 945, 10395, 135135, 2027025, 34459425, 654729075]


We've defined a composite function from the prod() and alt_range() functions
shown previously. The function f2 is semifactorial or double factorial, n!!. The value
of the function f2 is built by mapping our small n21() function applied to the seq1
sequence. This creates a new sequence. We then applied the semi_fact function to
this new sequence to create a sequence of 2 1n+ !! values that parallels the sequence
of n! values.

Free download pdf