Idea : Expression Type

Don Clugston dac at nospam.com.au
Thu Feb 1 06:29:57 PST 2007


Kyle Furlong wrote:
> Andrei Alexandrescu (See Website for Email) wrote:
>> Xinok wrote:
>>> I've held off this idea for a little while now, but I think it could
>>> really be a nice addition to D.
>>>
>>> Expressions are basically aliases which can accept arguments. Unlike
>>> aliases though, an expression can accept non-const arguments.
>>>
>>> expression mul(a, b) = a * b; // Syntax is different from aliases,
>>> for good reason...
>>>
>>> int main(){ int a = 35, b = 62; a = mul(a, b); }
>>>
>>> 'mul' isn't a constant expression. The expression is inlined into the
>>> code, it doesn't call a function.
>>>
>>> So basically, expressions are inline functions. BUT, because D lacks
>>> references (which I'll never be able to understand), functions can't
>>> return l-values. Expressions can be treated as so though.
>>
>> Walter had the idea of allowing an expression to bind to an alias, and
>> to allow the following:
>>
>> template mul(alias a, alias b)
>> {
>>   alias (a * b) mul;
>> }
>>
>> with the effect that you want. (The parens are there to keep alias
>> happy, not to prevent breakage of order of operations.)
>>
>>> One example of a recent post, the max function: expression max(a, b)
>>> = a > b ? a : b; Can handle any and all types, and you can use it as
>>> an l-value.
>>
>> Nah, that won't work. It will doubly evaluate one of its arguments. But
>> the feature will allow very simple implementation of my varargs_reduce
>> and varargs_reduce_parallel primitives, e.g.:
>>
>> template varargs_reduce(alias fun)
>> {
>>   template impl(alias args...)
>>   {
>>     static if (args.length == 2)
>>       alias fun(args) impl;
>>     else
>>       alias impl!(fun(args[0], args[1]), args[2..$]) impl;
>>   }
>> }
>>
>> This has a similar structure to the varargs_reduce that I posted a while
>> ago, except that it doesn't need to do any type inference - it just
>> replaces the expression and lets the compiler take care of the rest.
>>
>>
>> Andrei
> 
> This seems to me to be an obvious good extension to the template system. 
> With the ability to pass aliases into the template, you gain arbitrary 
> and easy expression composition.

The name mangling looks tricky. I think an expression alias would have 
to behave like a typedef: given
alias (a*b) X;
alias (a*b) Y;
X and Y would not be the same.
A name mangling scheme for an arbitrary expression would be a bit of a 
nightmare.



More information about the Digitalmars-d mailing list