Question of delegate literals and return from function(GDC, DMD, LDC)

downs default_357-line at yahoo.de
Sun Feb 1 04:43:02 PST 2009


amaury pouly wrote:
> Hello,
> I have a little question about D: I want to have a function returning a delegate and more precisely a delegate literal that uses one of the arguments of the function. Here is an example:
> 
> int delegate(int) test(int[] tab)
> {
>     return (int d)
>     {
>         int sum;
>         foreach(i;tab)
>             sum+=i*d;// stupid computation
>         return sum;
>     };
> }
> 
> int main()
> {
>     auto res=test([1,2,3,4,5,6])(4);
>     return res;
> }

tools version:

import tools.base, std.stdio;

int delegate(int) test(int[] tab) {
	return tab /apply/ (int[] tab, int d) {
		int sum;
		foreach (i; tab) sum += i*d;
		return sum;
	};
}

void main() {
	auto res = test([1,2,3,4,5,6])(4);
	writefln(res);
}



More information about the Digitalmars-d mailing list