Idea : Expression Type

Johan Granberg lijat.meREM at OVE.gmail.com
Wed Jan 31 23:31:04 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.
> 
> 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.

votes++

This is a good idea and could really complement mixins in a nice way.
What should the limits of this syntax be? should this be allowed.

//declared as
expression loop(a,b) = foreach(i,s,a)b[i]=s;

//used as
char[] foo=new char[10];
char[] bar=new char[10];
loop(foo,bar);

to be able to do this would be intresting as it could allow for some
powerfull syntax abstractions.

Another intresting case would be.

//declared as this
expression mix = AMixin!(bool)(5);

//used like this
mix;

here mix would be a mixin doing some work rather than declaring variables
and I would expect that the expression have there own scope so that no
mixin variables is leaked into the surrounding namespace.




More information about the Digitalmars-d mailing list