Search⌘ K

A List Of Functions

Explore how to abstract pluralization logic using pairs of match and apply functions in Python. Learn to simplify code by managing rules as function objects and iterating through them effectively.

We'll cover the following...

Now you’re going to add a level of abstraction. You started by defining a list of rules: if this, do that, otherwise go to the next rule. Let’s temporarily complicate part of the program so you can simplify another part.

Python 3.5
import re
def match_sxz(noun):
return re.search('[sxz]$', noun)
def apply_sxz(noun):
return re.sub('$', 'es', noun)
def match_h(noun):
return re.search('[^aeioudgkprt]h$', noun)
def apply_h(noun):
return re.sub('$', 'es', noun)
def match_y(noun): #①
return re.search('[^aeiou]y$', noun)
def apply_y(noun): #②
return re.sub('y$', 'ies', noun)
def match_default(noun):
return True
def apply_default(noun):
return noun + 's'
rules = ((match_sxz, apply_sxz), #③
(match_h, apply_h),
(match_y, apply_y),
(match_default, apply_default)
)
def plural(noun):
for matches_rule, apply_rule in rules: #④
if matches_rule(noun):
return apply_rule(noun)

① Now, each match rule is its own function which returns the results of calling the re.search() function.

② Each apply rule is also its own function which calls the re.sub() function to apply the appropriate pluralization rule.

③ Instead of having one function (plural()) with multiple rules, you have the rules data structure, which is a sequence of pairs of functions.

④ Since the rules have been ...