[Tutor] Not understanding this code example. Help, please.

Alan Gauld alan.gauld at btinternet.com
Sat Feb 13 10:27:42 CET 2010

"Eduardo Vieira" <eduardo.susan at gmail.com> 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...


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.


Alan Gauld
Author of the Learn to Program web site

More information about the Tutor mailing list