function operators
James A. H. Skillen
jahs at jahs.org
Mon Nov 26 20:43:34 EST 2001
Has anyone ever wished that Python had operators defined on functions?
For example, suppose you want the function f(x) = cos(x) + sin(x).
You could do:
def f(x):
return cos(x) + sin(x)
or
f = lambda x: cos(x) + sin(x)
but wouldn't:
f = cos + sin
be *much* nicer?
Similarly for *, -, /, etc.
Taking the idea of PEP 211 further, we could have the "outer product"
operator "@" work on functions too.
So
f = cos @ sin
would be equivalent to
f = lambda x,y: (cos(x), sin(y))
There is also another tremendously useful operator on functions:
composition.
For want of a better symbol, how about a new keyword "on" to be
composition.
So to get the function f(x) = cos(sin(x)) I could do
f = cos on sin
Why? Well this is useful if you use map, filter etc.
If I wanted to apply f as above to {0, ..., 9} then at the moment I
could do
map(cos, map(sin, range(10)))
or
map(lambda x: cos(sin(x)), range(10))
but with the new syntax I could write
map(cos on sin, range(10))
which is much clearer.
These are just trivial examples, but in conjunction with the car and cdr
functions it becomes powerful. For example, cadr = car on cdr.
Does this make sense, or have I been doing too much mathematics? ;-)
--
James A. H. Skillen - jahs at jahs.org
4th year MMath Mathematics undergraduate,
University of Warwick, UK.
More information about the Python-list
mailing list