Semantics of ^^
bearophile
bearophileHUGS at lycos.com
Tue Dec 8 03:16:17 PST 2009
Don:
> Based on everyone's comments, this is what I have come up with:
Looks good.
> * If y == 0, x ^^ y is 1.
> * If both x and y are integers, and y > 0, x^^y is equivalent to
> { auto u = x; foreach(i; 1..y) { u *= x; } return u; }
You can rewrite both of those as:
{ typeof(x) u = 1; foreach (i; 0 .. y) { u *= x; } return u; }
> (1) Although the following special cases could be defined...
> * If x == 1, x ^^ y is 1
> * If x == -1 and y is even, x^^y == 1
> * If x == -1 and y is odd, x^^y == -1
> ... they are not sufficiently useful to justify the major increase in
> complexity which they introduce.
This is not essential:
(-1)**n is a common enough shortcut to produce an alternating +1 -1, you can see it used often enough in Python code (and in mathematics). This search gives 433 results:
http://www.google.com/codesearch?q=\%28-1\%29\s*\*\*\s*[0-9a-zA-Z%28]+lang%3Apython
When used for this purpose (-1) is always compile time constant, so the compiler can grow a simple rule the rewrites:
(-1) ^^ n
as
(n & 1) ? -1 : 1
Bye,
bearophile
More information about the Digitalmars-d
mailing list