Functional Python Programming

(Wang) #1
Chapter 14

Here's our first function that computes the product:


import operator


prod = myreduce(operator.mul)


This is based on our curried myreduce() function that was defined previously.
It uses the operator.mul() function to compute a "times-reduction" of an iterable:
we can call a product a times-reduce of a sequence.


Here's our second curried function that will produce a range of values:


@curry


def alt_range(n):


if n == 0: return range(1,2) # Only 1


if n % 2 == 0:


return range(2,n+1,2)


else:


return range(1,n+1,2)


The result of the alt_range() function will be even values or odd values. It will
have only values up to (and including) n, if n is odd. If n is even, it will have only
even values up to n. The sequences are important for implementing the semifactorial
or double factorial function, n!!.


Here's how we can combine the prod() and alt_range() functions into a new
curried function:





semi_fact= prod * alt_range








semi_fact(9)





945


The PyMonad * operator here combines two functions into a composite function,
named semi_fact. The alt_range() function is applied to the arguments. Then,
the prod() function is applied to the results of the alt_range function.


By doing this manually in Python, we're effectively creating a new lambda object:


semi_fact= lambda x: prod(alt_range(x))


The composition of curried functions involves somewhat less syntax than creating
a new lambda object.


Ideally, we would like to use functional composition and curried functions like this:


sumwhile= sum * takewhile(lambda x: x > 1E-7)

Free download pdf