Callbacks or similar?

Lemonfiend Lemon at fie.nd
Sat Feb 16 12:56:56 PST 2013


Hi,

I'm looking for a way to do call different functions within a 
loop, so I won't have to write multiple functions with the same 
looping mechanism.
I'm not sure if I'm explaing this very well, but this very simple 
example should clarify:

void foo(int[] arr)
{
	foreach(int val; arr)
	{
		switch(val)
		{
			case 0:
				// call bar(val)
			break;

			case 1:
				// call barOther(val)
			break;

			default:
				throw new Exception("foo");
		}
	}
}


Now, this works, but it doesn't have my preference. I would 
prefer to use something like this:

void foo(int[] arr, int cmp, callback func(int))
{
	foreach(int val; arr)
	{
		if(val == cmp)
			func(val);
	}
}


How can I do this in D?
Or, is there a better way?

Thanks :)


More information about the Digitalmars-d-learn mailing list