Operators for everything (was Re: Operators for matrix)

Huaiyu Zhu hzhu at users.sourceforge.net
Wed Jul 26 19:34:53 EDT 2000


On Mon, 24 Jul 2000 21:38:36 -0500, Paul Prescod <paul at prescod.net> wrote:
>> 
>> If @add does not need to be hard coded in C, why @+ need so?  
>
>Neither needs to be hard-coded into the grammar. The parser could always
>recognize them from the leading @-symbol. This is different from your
>earlier proposals where *any sequence of symbols* could be an operator.
>That's quite different.

Although the patch I got adds a set of operators with different symbols, it
has always been clear that one generic way of adding new operators is more
preferable, as these operators are very similar to existing math operators.

>Nevertheless, I would be extremely reluctant to add a feature that would
>encourage people to do @++, @-- @+* and so forth. @increment is not so
>bad. @decrement is not so bad. @positive_mul (whatever that might mean
>in some particular domain) is not so bad.

I don't think many people are proposing these complicated operators as math
operators.  The main criteria is that they look as similar to the existing
math operators as possible.

>I think name-based binary operators are actually pretty neat and can be
>used very Pythonically. IMO, they are the right compromise between
>terseness and legibility.

For math operators the @id form looks too heavy.  Compare the following two:

(1 @add 2) @mul 3 @sub 4 == (10 @div 2) @pow 1

(1+2)*3 - 4 == (10/2)**1

The symbol @ does not work out well with symbolic operators, either.  In
tightly written code, like abc at +def, the @ is visually associated with the
preceding identifier rather than the operator. The alternative ~op looks
much more familiar:

(1~+2)~*3 ~- 4 == (10~/2)~^1

But since this is the "operator for everything" thread, may I suggest using
~+ ~- ~* ~/ operators for math, and @name @identifier operators for
everything else?

The parser would have similar difficulty recognizing either form.  Only two
opcodes need to be added, one for ~op, another for @id, instead of one for
each of the new operators.  I do not know about the run time efficiency. But
since current + can be overloaded with operator.__add__, I would imagine
that in terms of efficiency, ~op can be made to be similar to existing
operators, while @id is similar to existing function calls.

Huaiyu



More information about the Python-list mailing list