Generic vector aggregates

Joseph A Knapka jknapka at earthlink.net
Mon Jul 8 21:46:34 EDT 2002


Ingo Blank wrote:
> 
> Hi,
> 
> I want to implement a generic vector aggregate function for dyadic operators
> like this:

I believe the built-in reduce() function does exactly what
you want (that is, it performs your aggregate() task).
As for naming arithmetic operators, have a look at the
"operator" module :-)

Cheers,

-- Joe

> ## -- dyadic operators (primitives)
> 
> def add(a,b):
>  return a + b
> 
> def  mul(a,b):
>  return a * b
> 
> def inc(a,b):
>  return a + 1
> 
> ## -- generic aggregate
> 
> def aggregate(f,v,start=0):
>  a = start
>  for x in v:
>   a = apply(f,(a,x))
>  return a
> 
> ## -- 2nd order callers
> 
> def sum(v):
>  return aggregate(add,v,0)
> 
> def prod(v):
>  return aggregate(mul,v,1)
> 
> def count(v):
>  return aggregate(inc,v,0)
> 
> ... and so on...
> 
> Q:  How can I refer to the built in arithmetic operators "+","*" etc.
>     This would save the additional dispatching step, without the need to
> call
>     "add","mul" etc.
> 
> Thanks
> 
> --ingo
> voy NG arktb QBG qr [ rot13 ]
> 
> PGP PublicKey
> http://pgp.mit.edu:11371/pks/lookup?op=get&search=0x18B44974

-- 
   "Thanks to Microsoft, I am now blind in both eyes. They have
    rolled back in my head so many times this week that they
    are apparently stuck there now."
      - Jonathan Rickman, regarding M$ anti-open-source PR.



More information about the Python-list mailing list