A possible solution for the opIndexXxxAssign morass

Bill Baxter wbaxter at gmail.com
Wed Oct 14 05:58:19 PDT 2009


On Wed, Oct 14, 2009 at 12:48 AM, Lars T. Kyllingstad
<public at kyllingen.nospamnet> wrote:
> Don wrote:
>>
>> Andrei Alexandrescu wrote:
>>>
>>> Right now we're in trouble with operators: opIndex and opIndexAssign
>>> don't seem to be up to snuff because they don't catch operations like
>>>
>>> a[b] += c;
>>>
>>> with reasonable expressiveness and efficiency.
>>>
>>> Last night this idea occurred to me: we could simply use overloading with
>>> the existing operator names. Consider:
>>>
>>> a += b
>>>
>>> gets rewritten as
>>>
>>> a.opAddAssign(b)
>>>
>>> Then how about this - rewrite this:
>>>
>>> a[b] += c
>>>
>>> as
>>>
>>> a.opAddAssign(b, c);
>>>
>>> There's no chance of ambiguity because the parameter counts are
>>> different. Moreover, this scales to multiple indexes:
>>>
>>> a[b1, b2, ..., bn] = c
>>>
>>> gets rewritten as
>>>
>>> a.opAddAssign(b1, b2, ..., bn, c)
>>>
>>> What do you think? I may be missing some important cases or threats.
>>>
>>>
>>> Andrei
>>
>> Well timed. I just wrote this operator overloading proposal, part 1.
>> http://www.prowiki.org/wiki4d/wiki.cgi?LanguageDevel/DIPs/DIP7
>> I concentrated on getting the use cases established.
>>
>> The indexing thing was something I didn't have a solution for.
>>
>> BTW we need to deal with slices as well as indexes. I think the way to do
>> this is to make a slice into a type of index.
>
>
> I like the idea of enforcing relationships between operators. In fact, I
> think we can take it even further, and require that operator overloading in
> general *must* follow mathematical rules, and anything else leads to
> undefined behaviour. For example, if n is an integer, a and b are scalars,
> and x and y are general types, the compiler should be free to rewrite
>
>         n*x  <-->  x + x + ... + x    <-->  2*x + 2*x + ...
>        x^^n  <-->  x * x * ... * x    <-->  x^^2 * x^^2 * ...
>   x/a + y/b  <-->  (b*x + a*y)/(a*b)
>
> and so on, based on what it finds to be the most efficient operations. (Note
> how I snuck my favourite suggestion for an exponentiation operator in there.
> I *really* want that.)

You have to be careful when you go rewriting mathematical expressions
on the computer, though.  The numerical error for two mathematically
identical expressions can be quite different when evaluated in finite
precision arithmetic.

I'd love an exponentiation operator, too.

--bb



More information about the Digitalmars-d mailing list