operator on functions
Ben Wolfson
wolfson at uchicago.edu
Fri Apr 6 12:47:34 EDT 2001
In article <9akpvh$74k$1 at news.mathworks.com>, "Joshua Marshall"
<jmarshal at mathworks.com> wrote:
> Szalay Zoltan <szz at philoslabs.com> wrote:
>> Hi everybody out there!
>
>> It would be a nice feature of Python syntax providing an operator to
>> compose a function from another two:
>> h=f*g . I mean (f*g)(x)=f(g(x).
>
> Though maybe a little thought needs to go into multiple arguments (to
> f):
>
> (f*g)(x) => f(g(x))
>
> -vs-
>
> apply(f*g, x) => apply(f, apply(g, x))
>
> or some hybrid.
This seems to work:
from __future__ import nested_scopes
class Function:
def __init__(self, f):
self.f=f
def __call__(self, *a, **k):
return self.f(*a, **k)
def __mul__(self, o):
return _compose(self, o)
def __rmul__(self, o):
return _compose(o, self)
def compose(f, g):
def composed(*a, **k):
result = g(*a, **k)
if type(result) is not type(()):
result = (result,)
return f(*result)
return composed
>>> import compose
>>> g = compose.Function(lambda a,b: (a+b, a*b, a-b)
>>> f = lambda a,b,c: ((a+b)*c, (a-b)/c)
>>> (f*g)(1,2)
(-5, -1)
>>> (g*f)(1,2,3)
(8, -9, 10)
>>> h = compose.Function(lambda a,b: a+b)
>>> i = lambda a: (-a, a+4)
>>> (h*i)(2)
4
>>> (i*h)(2,4)
(-6, 10)
--
Barnabas T. Rumjuggler
The women come and go,
Speaking of the Regis Philbin Show
-- Joe Frank
More information about the Python-list
mailing list