"Eduardo Vieira" <[email protected]> wrote

def build_match_and_apply_functions(pattern, search, replace):
   def matches_rule(word):
       return re.search(pattern, word)
   def apply_rule(word):
       return re.sub(search, replace, word)
   return (matches_rule, apply_rule)

patterns = \
 (
   ('[sxz]$',           '$',  'es'),
   ('[^aeioudgkprt]h$', '$',  'es'),
   ('(qu|[^aeiou])y$',  'y$', 'ies'),
   ('$',                '$',  's')
 )
rules = [build_match_and_apply_functions(pattern, search, replace)
        for (pattern, search, replace) in patterns]

def plural(noun):
   for matches_rule, apply_rule in rules:
       if matches_rule(noun):
           return apply_rule(noun)

My question is "baby" assigned to "word" in the inner function? It's a
little mind bending for me...

Yes.

rules is a list comprehension that builds a list of 3 pairs of functions.
These functions are returned from the first function above.
Those functions both take a word as an argument.

in plural it iterates over these pairs of functions and applies noun as the argument to both functtions, so noun gets applied as the word parameter to both functions.

And yes it is a little mind bending and there are more straighforward ways to code it, but they require more code and don't show off the use of higher order functions. It depends on what the book is actually trying to explain here whether this approach is sensible or not.

HTH,

--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/

_______________________________________________
Tutor maillist  -  [email protected]
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor

Reply via email to