www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Error when using delegate in foreach

reply Max Samuha <maxter i.com.ua> writes:
I've tried to use a delegate as aggregate in foreach:

void main()
{
	auto dg = delegate(inout int i)
		{
			static int j;
			if (j > 1000) return 1;
			i = j++;
			return 0;
		};

	foreach (int i; dg)
	{
		writefln(i);
	}
}

The code gives the error:

test.d(15): cannot implicitly convert expression (__foreachbody2) of
type int delegate(inout int i) to int

test.d(15): cast(int)__foreachbody2 is not an lvalue

What am I doing wrong?
Oct 17 2006
next sibling parent Carlos Santander <csantander619 gmail.com> writes:
Max Samuha escribió:
 I've tried to use a delegate as aggregate in foreach:
 
 void main()
 {
 	auto dg = delegate(inout int i)
 		{
 			static int j;
 			if (j > 1000) return 1;
 			i = j++;
 			return 0;
 		};
 
 	foreach (int i; dg)
 	{
 		writefln(i);
 	}
 }
 
 The code gives the error:
 
 test.d(15): cannot implicitly convert expression (__foreachbody2) of
 type int delegate(inout int i) to int
 
 test.d(15): cast(int)__foreachbody2 is not an lvalue
 
 What am I doing wrong?

I can't try it (Mac OS X here), but maybe your foreach should be: foreach (inout int i; dg) Just a guess. -- Carlos Santander Bernal
Oct 17 2006
prev sibling next sibling parent Tom S <h3r3tic remove.mat.uni.torun.pl> writes:
Max Samuha wrote:
 I've tried to use a delegate as aggregate in foreach:
 
 void main()
 {
 	auto dg = delegate(inout int i)
 		{
 			static int j;
 			if (j > 1000) return 1;
 			i = j++;
 			return 0;
 		};
 
 	foreach (int i; dg)
 	{
 		writefln(i);
 	}
 }
 
 The code gives the error:
 
 test.d(15): cannot implicitly convert expression (__foreachbody2) of
 type int delegate(inout int i) to int
 
 test.d(15): cast(int)__foreachbody2 is not an lvalue
 
 What am I doing wrong?

I think that the problem is that 'dg' should be of type 'int delegate(int delegate(inout int))'.
Oct 17 2006
prev sibling parent reply Karen Lanrap <karen digitaldaemon.com> writes:
Max Samuha wrote:

 What am I doing wrong?

Semms you mean something like this: import std.stdio; void main() { auto dg = delegate (int delegate( inout int) dgp) { static int j=0; int res=0; while( j < 15){ j++; res= dgp(j); if(res) break; } return res; }; foreach (int i; dg) { writefln(i); } }
Oct 17 2006
parent Max Samuha <maxter i.com.ua> writes:
On Tue, 17 Oct 2006 23:57:46 +0000 (UTC), Karen Lanrap
<karen digitaldaemon.com> wrote:

Max Samuha wrote:

 What am I doing wrong?

Semms you mean something like this: import std.stdio; void main() { auto dg = delegate (int delegate( inout int) dgp) { static int j=0; int res=0; while( j < 15){ j++; res= dgp(j); if(res) break; } return res; }; foreach (int i; dg) { writefln(i); } }

Yes, right. Thanks a lot
Oct 18 2006