Functional Python Programming

(Wang) #1

Higher-order Functions


We can define a function as follows:


def first(predicate, collection):


for x in collection:


if predicate(x): return x


We've iterated through the collection, applying the given predicate function. If the
predicate is True, we'll return the associated value. If we exhaust the collection,
the default value of None will be returned.


We can also download a version of this from PyPi. The first module contains a
variation on this idea. For more details visit: https://pypi.python.org/pypi/first.


This can act as a helper when trying to determine whether a number is a prime
number or not. The following is a function that tests a number for being prime:


import math


def isprimeh(x):


if x == 2: return True


if x % 2 == 0: return False


factor= first( lambda n: x%n==0,
range(3,int(math.sqrt(x)+.5)+1,2))


return factor is None


This function handles a few of the edge cases regarding the number 2 being a prime
number and every other even number being composite. Then, it uses the first()
function defined above to locate the first factor in the given collection.


When the first() function will return the factor, the actual number doesn't matter.
Its existence is all that matters for this particular example. Therefore, the isprimeh()
function returns True if no factor was found.


We can do something similar to handle data exceptions. The following is a version of
the map() function that also filters bad data:


def map_not_none(function, iterable):


for x in iterable:


try:


yield function(x)


except Exception as e:


pass # print(e)

Free download pdf