www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - d optimization: delegates vs. mixin

reply zoli <zoli freemail.hu> writes:
Can the compiler optimize the delegates (foo) to form an inline code, or the
mixin version is prefered?

module a;

import std.stdio;

void foo2( string s )()
{

	for( int i = 0 ; i < 10; i++ )
	{
		mixin( s );
	}		
}

void foo( void delegate(int) pDg )
{
	for( int i = 0 ; i < 10; i++ )
	{
		pDg( i );
	}		
} 

void main()
{
	foo( (int a){ writeln( a ); } );
	foo2!("writeln( i );")();
}

Thank you 1
Oct 21 2009
parent reply bearophile <bearophileHUGS lycos.com> writes:
zoli:
 Can the compiler optimize the delegates (foo) to form an inline code, or the
mixin version is prefered?<

Today D compilers are in general not smart enough yet (like the Scala compiler, for example) to inline delegates. But there's an alternative to string mixins, in D2 you can pass a templated function, even one where you omit the type of the arguments :-) There's no shortage of tricks in D2. Bye, bearophile
Oct 21 2009
parent reply zoli <galap freemail.hu> writes:
bearophile Wrote:

 zoli:
 Can the compiler optimize the delegates (foo) to form an inline code, or the
mixin version is prefered?<

Today D compilers are in general not smart enough yet (like the Scala compiler, for example) to inline delegates. But there's an alternative to string mixins, in D2 you can pass a templated function, even one where you omit the type of the arguments :-) There's no shortage of tricks in D2.

Thank you. Could you provide a sample or a link ? Sorry, i know it's a d.learn topic..., Offtopic: Is it possible to alter the web interface of the news to change newsgroups during composition ?
Oct 21 2009
parent bearophile <bearophileHUGS lycos.com> writes:
zoli:

 Thank you. Could you provide a sample or a link ?

Silly D2 code: import std.stdio: writeln; void table(alias Mapper, T)(T[] arr) { foreach (el; arr) writeln(Mapper(el)); } void main() { table!((x){ return x * x;})([2, 3, 4]); } I don't like that code a lot, I'd like the D compiler to be smarter, so the programmer can avoid such silly tricks, and the programmer can program in a more functional style (where you use *functions*).
 Sorry, i know it's a d.learn topic..., 

Yep. Better to ask such things there.
 Offtopic: Is it possible to alter the web interface of the news to change
newsgroups during composition ?<

I don't know. Probably not. Bye, bearophile
Oct 21 2009