www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Is there something like "apply"?

reply =?iso-8859-1?Q?Robert_M._M=FCnch?= <robert.muench saphirion.com> writes:
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
next sibling parent reply "Adam D. Ruppe" <destructionator gmail.com> writes:
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
parent =?iso-8859-1?Q?Robert_M._M=FCnch?= <robert.muench saphirion.com> writes:
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
prev sibling parent =?UTF-8?B?QWxpIMOHZWhyZWxp?= <acehreli yahoo.com> writes:
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