Idea : Expression Type

Xinok xnknet at gmail.com
Wed Jan 31 22:08:48 PST 2007


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.

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.


Expressions can also be used for simpler operations, such as dereferencing an array or pointer, to make code easier to read and write:
int* ptr = new int;
expression exp = *ptr;
exp = 62;

int[] arr = [15, 30, 45, 60];
expression val = arr[2];
val = 30;


Expressions can also handle constants, so it could be used as an alias which can take arguments.
(Maybe require const property?)
const expression ptr(T) = T*;


-- Expressions are NOT mixins! You can't use undeclared symbols in an expression.
-- Expressions are NOT functions! The expression is inlined into the code.



More information about the Digitalmars-d mailing list