binding arbitrary function arguments

Thomas thomas.h at ya.com
Wed Jun 27 12:18:52 PDT 2007


Hello!

I'm trying to familiarize myself a bit with D translating idioms I'm used to from other languages. Binding function arguments I ran into a problem.

Is there a "good" way to bind an arbitrary function argument?
I implemented "bind1st", "bind2nd", ... which was not too difficult, but failed when trying to implement "bindNth". Well, that is I managed to write only a rather "ugly" version:
Given for example
  int plus(int a1, int a2)...
I can do
  auto plus_four = bind1st(&plus, 4);
  plus_four(1); // => 5
but I cannot think of a way to achieve
  auto plus_four = bindNth(&plus, 1, 4); // binding first argument to 4
  plus_four(1); 

All I got so far is:
  auto plus_four = bind!(1).Nth(&plus, 4);

Any suggestions would be very welcome.
Thanks in advance,
Thomas


The code:
template bind(int I)
{
	R delegate(U) Nth(R, A, U...)(R delegate(A, U) dg, A arg)
	{
		struct binder
		{
			R delegate(A, U) dg_m;
			A arg_m;

			R call(U u)
			{
				return dg_m(u[0..I-1], arg_m, u[I-1..u.length]);
			}
		}
	
		binder* b = new binder;
		b.dg_m = dg;
		b.arg_m = arg;
		return &b.call;
	}
}





More information about the Digitalmars-d-learn mailing list