More on semantics of opPow: return type

bearophile bearophileHUGS at lycos.com
Mon Dec 7 15:50:44 PST 2009


Just few comments.

Don:

> Operations involving integers are far less obvious (and are actually 
> where a major benefit of an operator can come in).

The pow operator in Python seems to give good results (this also shows why dynamic typing can be useful, because the return type of a function like pow can change according to the value of its arguments):

>>> 2 ** 10
1024
>>> type(2 ** 10)
<type 'int'>
>>> 10 ** 0.5
3.1622776601683795
>>> 10 ** -2
0.01
>>> -5 ** 3
-125
>>> -5 ** 0.1
-1.174618943088019
>>> (-5+0j) ** 0.1
(1.1171289999875864+0.36297721532893706j)
>>> 117 ** 22
3162925469512000273381545759794499423612250089L
>>> (117 ** 22) % 11
5L
>>> pow(117, 22, 11) # third is optional faster mod
5


> I strongly suspect that x^^y, where x and y are integers, and the value 
> of y is not known at compile time, is an extremely rare operation.

This shows about 4000 results for Python, it's not an extremely rare operation:
http://www.google.com/codesearch?q=[0-9a-zA-Z%29]\s*\*\*\s*[a-zA-Z%28]+lang%3Apython

Having a pow operator is quite handy, in Python I use ** often enough, but it's not necessary, functions too can be enough.
But here some optimizations done by the compiler are really useful. For example I can't use pow(foo(),2) in the middle of a hot loop if I know the compiler will not surely translate it with a single multiplication of the result of foo(), etc.. It's like with tail-call optimization: you can write different code if you know it's present. If you aren't sure it's present it's not very useful.

Bye,
bearophile



More information about the Digitalmars-d mailing list