Idea : Expression Type
Vladimir Panteleev
thecybershadow at gmail.com
Fri Feb 2 02:35:48 PST 2007
On Thu, 01 Feb 2007 08:08:48 +0200, Xinok <xnknet at gmail.com> 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);
> }
votes++. However, why not go all the way and implement inline functions? That is, functions which are inlined in the expression using them.
These would have the following advantages:
* using a simple syntax (an "inline" attribute for the function);
* since no calls to the function are made, the compiler can decide when to use lazy argument evaluation and when to cache the results;
* since it's a function, it's possible to use complex instructions (blocks, loops, etc.)
* the code (arguments, return value) simply direct the data flow - there is no real stack frame, the return value is passed immediately and evaluated with the context, etc. Unless there is a strong barrier in the compiler between compiling expressions and statements (so that compound statements could be inlined in expressions), it shouldn't be hard to implement either.
In contrast to the above method, however, it won't be possible to use the same expression/inline function with different types. For example, using the syntax above,
expression div(a, b) = a/b;
int main(){
int i1 = 65, i2 = 32, i3;
i3=div(i1, i2);
float f1 = 6.5, f2 = 3.2, f3;
f3=div(i1, i2);
}
won't be directly possible with inline functions - but is easily done by enclosing the inline function in a template (not unlike regular functions):
template div(T)
{ inline T div(T a, T b) { return a/b; }
}
void main()
{ writefln(div!(int)(5,2));
writefln(div!(float)(5.5,2.1));
}
What do you think?
--
Best regards,
Vladimir mailto:thecybershadow at gmail.com
More information about the Digitalmars-d
mailing list