Idea : Expression Type
Andrei Alexandrescu (See Website For Email)
SeeWebsiteForEmail at erdani.org
Wed Jan 31 23:06:43 PST 2007
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 varargs_reduce(alias args...)
{
static if (args.length == 2)
alias fun(args) varargs_reduce;
else
alias varargs_reduce!(fun(args[0], args[1]), args[2..$])
varargs_reduce;
}
}
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.
(I'm a bit unclear about the workings of the double promotion of the
'varargs_reduce' symbol, but that's a minor point.)
Andrei
More information about the Digitalmars-d
mailing list