Bill Baxter wrote:
On Fri, Aug 7, 2009 at 3:50 AM, Lars T.
Kyllingstad<pub...@kyllingen.nospamnet> wrote:
In the 'proposed syntax change' thread, Don mentioned that an exponentiation
operator is sorely missing from D. I couldn't agree more.
Daniel Keep has proposed the syntax
a*^b
while my suggestion was
a^^b
Neither of the natural candidates, a^b and a**b, are an option, as they are,
respectively, already taken and ambiguous.
"Why do we need this?" you say. "Isn't pow(a,b) good enough?" And yes,
pow(a,b) is just as good as mul(a,b) or div(a,b), but we don't use those, do
we? Exponentiation is a very common mathematical operation that deserves its
own symbol. Besides, bearophile has pointed out several optimisations that
the compiler can/must perform on exponential expressions.
He also proposed that the overload be called opPower.
What do you think?
I'm all for it.
But if we can't get that, then it might be nice to have at least
squaring and cubing template functions in std.math. Squaring numbers
is so common it deserves a direct way. It always annoys me when I
have to write
float x = (some expression);
float x2 = x*x;
When I'd like to be able to just write (some expression)^^2.
sqr(some expression) would be ok, too. It's odd that sqrt and cbrt
exist in the std C math library but not their inverses.
Yes, it's powers of 2 and 3 that are 90% of the use cases.
Squaring is a really common operation (more common than xor). An
optimising compiler always needs to recognize it.
I found this list of languages with an exponentiation operator:
# x ↑ y: Algol, Commodore BASIC
# x ^ y: BASIC, J, Matlab, R, Microsoft Excel, TeX (and its
derivatives), Haskell (for integer exponents), and most computer
algebra systems
# x ** y: Ada, Bash, Fortran, FoxPro, Perl, Python, Ruby, SAS, ABAP,
Haskell (for floating-point exponents), Turing
# x * y: APL
--bb
I personally don't understand why anyone would like ** as an
exponentiation operator. The only thing in its favour is that that's
what Fortran did. And Fortran only used it because it had almost no
characters to choose from. ↑ is the best (yup, I had a C64).
^ is the next best, but unfortunately C grabbed it for xor. I think ^^
is the best available option.
Aside from the fact that x**y is ambiguous (eg, x***y could be x ** (*y)
or x * (*(*y)) ), I just think ^^ looks better:
assert( 3**3 + 4**3 + 5**3 == 6**3 );
assert( 3^^3 + 4^^3 + 5^^3 == 6^^3 );
Found an old discussion, pragma proposed ^^ and opPower:
http://www.digitalmars.com/d/archives/digitalmars/D/18742.html#N18742
The fact that exactly the same proposal came up again is encouraging --
it's moderately intuitive.
For overloading, by analogy to opAdd(), opSub(), opMul(), opDiv() it
should probably be opPow().