function operators
Hans Nowak
wurmy at earthlink.net
Mon Nov 26 21:05:39 EST 2001
"James A. H. Skillen" wrote:
>
> 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
Assuming this would ever be implemented, then it would work on "normal"
functions, but problems would occur with other callable objects. Most
notably, classes that override the + operator. In other words, if a and
b are instances of a class that implements both __add__ and __call__,
what would
f = a + b
mean? Would it mean
f = a.__add__(b)
or
f = lambda x: a(...) + b(...)
like with regular functions? Ambiguity occurs.
Then again, it may be possible to write a wrapper class that holds a
function, is callable through __call__, *and* implements __add__ and
other operators, that do what you want... I was going to give it a try,
but then I got high... ;-)
> 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.
But a compose function is easily defined; for example, in
1.5.2-compatible
code:
def compose(f, g):
return lambda x, f=f, g=g: f(g(x))
or in 2.1:
from __future__ import nested_scopes
def compose(f, g):
return lambda x: f(g(x))
...so whether it's worthwile to add an extra operator for this, is
doubtful.
> but with the new syntax I could write
>
> map(cos on sin, range(10))
It does look nice, though. :-)
> Does this make sense, or have I been doing too much mathematics? ;-)
Python isn't a functional language, but many features of such languages
can be implemented with a little trickery.
Regards,
--Hans
More information about the Python-list
mailing list