digitalmars.D.learn - Is there something like "apply"?
- =?iso-8859-1?Q?Robert_M._M=FCnch?= (12/12) Apr 28 2015 Hi, I have the following "problem": I have the parameters for a
- Adam D. Ruppe (13/13) Apr 28 2015 Easiest is to just do it by hand:
- =?iso-8859-1?Q?Robert_M._M=FCnch?= (7/23) Apr 28 2015 Yep, that's what I did. Really cool...
- =?UTF-8?B?QWxpIMOHZWhyZWxp?= (16/24) Apr 28 2015 import std.stdio;
Hi, I have the following "problem": I have the parameters for a function in an array. Now I want to call a function with a specific arity and use the parameters from the array to call it. Like this pseudo-code: args = [10, 20]; def foo(a, b): return a + b; print(foo(*args)); Is something like this possible in D? -- Robert M. Münch http://www.saphirion.com smarter | better | faster
Apr 28 2015
Easiest is to just do it by hand: foo(args[0], args[1]); This can also be automated with a bit of code in a lot of cases: import std.traits; ParameterTypeTuple!foo params; foreach(index, ref param; params) { params[index] = args[index]; } foo(params); Move that into a helper function and you can call it apply. You could also make that assignment in the loop to type conversion if you wanted, my jsvar.d does this to provide javascript-style functions with an apply method.
Apr 28 2015
On 2015-04-28 17:52:57 +0000, Adam D. Ruppe said:This can also be automated with a bit of code in a lot of cases: import std.traits; ParameterTypeTuple!foo params; foreach(index, ref param; params) { params[index] = args[index]; } foo(params); Move that into a helper function and you can call it apply.Adam, thanks a lot! That's what I need. Great stuff.You could also make that assignment in the loop to type conversion if you wanted, my jsvar.d does this to provide javascript-style functions with an apply method.Yep, that's what I did. Really cool... -- Robert M. Münch http://www.saphirion.com smarter | better | faster
Apr 28 2015
On 04/28/2015 10:48 AM, Robert M. Münch wrote:Hi, I have the following "problem": I have the parameters for a function in an array. Now I want to call a function with a specific arity and use the parameters from the array to call it. Like this pseudo-code: args = [10, 20]; def foo(a, b): return a + b; print(foo(*args)); Is something like this possible in D?import std.stdio; import std.typetuple; void foo(int i, string s, double d) { writefln("foo: %s %s %s", i, s, d); } void main() { auto args = TypeTuple!(42, "hello", 1.5); ++args[0]; args[1] ~= " world"; args[2] *= 3; foo(args); } Ali
Apr 28 2015