I l@ve RuBoard |

## 15.9 Composing FunctionsCredit: Scott David Daniels ## 15.9.1 ProblemYou need to construct a new function by composing existing functions (i.e., each call of the new function must call one existing function on its arguments, then another on the result of the first one). ## 15.9.2 SolutionComposition is a fundamental
operation between functions that yields a new function as a
result梩he new function must call one existing function on its
arguments, then another on the result of the first one. For example,
a function that, given a string, returns a copy that is lowercase and
does not have leading and trailing blanks, is the composition of the
existing class compose: '''compose functions. compose(f,g,x...)(y...) = f(g(y...),x...))''' def _ _init_ _(self, f, g, *args, **kwargs): self.f = f self.g = g self.pending = args[:] self.kwargs = kwargs.copy( ) def _ _call_ _(self, *args, **kwargs): return self.f(self.g(*args, **kwargs), *self.pending, **self.kwargs) class mcompose(compose): '''compose functions. mcompose(f,g,x...)(y...) = f(*g(y...),x...))''' TupleType = type(( )) def _ _call_ _(self, *args, **kwargs): mid = self.g(*args, **kwargs) if isinstance(mid, self.TupleType): return self.f(*(mid + self.pending), **self.kwargs) return self.f(mid, *self.pending, **self.kwargs) ## 15.9.3 DiscussionThe two classes in this recipe show two styles of function
composition. The only difference is when the second function,
compose(f,g, x...)(y...) = f(g(y...), x...) mcompose(f,g, x...)(y...) = f(*g(y...), x...) As in currying (see Recipe 15.8), this recipe's functions are for constructing functions from other functions. Your goal should be clarity, since there is no efficiency gained by using the functional forms. Here's a quick example for interactive use: parts = compose(' '.join, dir) When applied to a module, the callable we just bound to
I separated
In Python 2.2 (or 2.1 with def compose(f, g, *orig_args, **orig_kwds): def nested_function(*more_args, **more_kwds): return f(g(*more_args, **more_kwds), *orig_args, **orig_kwds) return nested_function This ## 15.9.4 See AlsoRecipe 15.8 for an example of currying (i.e., associating parameters with partially evaluated functions). |

I l@ve RuBoard |