[PEP draft 2] Adding new math operators

Huaiyu Zhu hzhu at localhost.localdomain
Wed Aug 9 15:10:37 EDT 2000


On Wed, 09 Aug 2000 17:32:46 GMT, Tim Hochberg <tim.hochberg at ieee.org> wrote:
>
> <gregory.lielens at fft.be> writes
> ...
> >Don't you fear the "backtracking" aspect, i.e. to have to track back the
> >code to check the types of A and B, before knowing the operation which
> >is perfromed by A 'op' B? 
> >I know this is already the case now, for example if A and B are strings,
> >A+B is a concatenation instead of an addition...Fair for me in this case
> >because I consider string and int to be quite different beasts (sorry
> >all perl-lovers :-)), and expect to be able to differentiate them by
> >context quite easily...
> >However, when making the 'op' behavior differ for two very close classes
> >(as array and matrix would obviously be), I think it could be a lot more
> >error-prone...Similar (worst?) to the classical "1/2 == 0 (oops - why
> >not 0.5?)" which pop up sometimes in this newsgroup...
>
>
>I believe this is why Konrad was suggesting that mixed operations
>would raise an error; this would more or less eliminate silent
>problems due to "backtracking". If you got at least one of the operand
>types correct, the result would either be correct or raise an
>error. So in a MatPy environment:
>
>a + b # OK
>a.E + b # ValueError
>a + b.E # ValueError
>a.E + b.E # OK
>

This is OK when the type is not persistent (so the .E and .M only appear
with the operands).  When it's persistent you could have

def f(a,b): return (a*b).M
def g(x): do a lot of things, y=z.E, eventually return y
c = f(a,b) # return matrix, doing matrixwise mul
... a lot of things in between
a = a.E
b = b.E
..... much later
d = f(a,b) # return matrix, but doing elementwise mul
a = a.M
b = b.M
e = f(g(a),g(b)) # return matrix, but doing elementwise mul

You have to remember what type each function is accepting and returning, and
have a mental picture of which part of your program have all matrixwise or
elementwise objects.

You also end up with expressions like

((a.E*b.E).M*(c.E*d.E).M).E + (x.M*y.M).E  # vs    (a~*b)*(c~*d) ~+ x*y
                                           # or    (a*b)~*(c*d) + x~*y
Huaiyu




More information about the Python-list mailing list