[PEP draft 2] Adding new math operators

Rainer Deyke root at rainerdeyke.com
Wed Aug 9 21:15:02 EDT 2000


"Huaiyu Zhu" <hzhu at localhost.localdomain> wrote in message
news:slrn8p362j.st.hzhu at rocket.knowledgetrack.com...
> On Wed, 09 Aug 2000 04:52:04 GMT, Rainer Deyke <root at rainerdeyke.com>
wrote:
> >A better solution would be to have a method for "elementwise" operations:
> >
> >class Pair:
> >  def __init__(self, first, second):
> >    self.first = first
> >    self.second = second
> >
> >  def elementwise(self, operation):
> >    return Pair(operation(self.first), operation(self.second))
>
> I don't follow you.  Suppose
> operation = add
> first = (1,2)
> second = (3,4)
>
> do you get (3,7) or (4,6)?  The latter is elementwise add.  Maybe I just
> missed something.

Right, it doesn't work in its present form.  Try this:

class Pair:
  def __init__(self, first, second):
    self.first = first
    self.second = second

  def elementwise(self, other, operation):
    return Pair(operation(self.first, other.first),\
      operation(self.second, other.second))

first = Pair(1, 2)
second = Pair(3, 4)
combined = first.elementwise(second, lambda x, y: x + y)

Of course 'elementwise' itself could be __magic__, such that it is
automatically invoked by special operators.

Proposed special syntax: <expr1> ~ <op1> <expr2> evaluates to
<expr1>.__elementwise__(<expr2>, lambda x, y: x <op1> y).  Note that ~
remains a separate token - this is for the benefit of the parser.  <op1> is
zero or more ~ symbols followed by a binary operator.  (Actually, __coerce__
should probably be used first.  __relementwise__ is unnecessary, but
<expr2>.__elementwise__(<expr1>, lambda x, y: y <op1> x) could be called if
<expr1>.__elementwise__ does not exist.)


--
Rainer Deyke (root at rainerdeyke.com)
Shareware action/role-playing games      -      http://rainerdeyke.com
"In ihren Reihen zu stehen heisst unter Feinden zu kaempfen" - Abigor





More information about the Python-list mailing list