[Python-Dev] Function Operators
Terry Reedy
tjreedy at udel.edu
Sun Jul 18 15:10:34 EDT 2010
>> Christopher Olah
>>> In mathematical notation, f*g = z->f(g(z)) and f^n = f*f*f... (n
>>> times). I often run into situations in python where such operators
>>> could result in cleaner code.
Python has a general mechanism for composing functions to make new
functions: the def statement. "z = f*g" is a special case operation
combining two compatible one-parameter parameter functions. In Python,
it is spelled
def z(x): return f(g(x))
The advantage of the latter is that it gives the resulting function
object a definition name attached to the function as an attribute, which
is important for error tracebacks.
This gets to a difference between math and computing. In math, 'z=f*f',
if it is not an equality claim ('z==f*g' in Python terms), defines 'z'
to mean the *pre-existing*, abstract, attribute-less function that can
also be denoted by 'f*g'. In Python (in particular), it would mean
"create a *new*, anonymous function object and associate it
non-exclusively with 'z'".
If f and g are not primitive functions but are compositions themselves,
then substituting the composition for g in the composition for f may
allow for simplification and greater efficiency. This consideration is
irrelevant in math, where computation happens instantaneously, or where
f*g is simply a set of ordered pairs, just like f and g (all with
instataneous lookup).
As for f^n, it is very rare in practice for n to be a fixed value more
than 2 or 3. For n==2, f^2 is simply f*f, see above. For n==3,
def f3(x): return f(f(f(x)))
has the advantage of creating one new function instead of two. I believe
larger values of n mostly arise in iteration to a fixed point or until
some other stopping point in reached.
Terry Jan Reedy
More information about the Python-list
mailing list