2
$\begingroup$

I have a function that need to be summed over all parameters given in a separate list.

f[x_,y_,z_,n_,i_]:= (*Some function*);
list={{n1,i1},{n2,i2},...};

I need to create another function that should look like:

g[x_,y_,z_]:=f[x,y,z,n1,i1] + f[x,y,z,n2,i2] + ...;

for any matching input of list. Is there any way to do it elegantly? I'm thinking about extracting the expression that I typed for f and store it as String then replace the n and i for each pairs in list.

Subquestion: Is there any way to extract the expression from given input?

$\endgroup$
3
  • 2
    $\begingroup$ Total[f[x, y, z, ##] & @@@ list] ought to work. $\endgroup$ Commented Jul 14, 2015 at 17:39
  • $\begingroup$ That works. Thanks! $\endgroup$
    – Hima
    Commented Jul 14, 2015 at 18:07
  • 1
    $\begingroup$ For the subquestion: not sure what you mean but if you want to prevent the argument of a function from being evaluated (so the expression is passed to the function in its original form), use something like SetAttributes[g, HoldAll]. But in your questions the only "expression" I see is in list, and Lists of that type aren't evaluated anyway, so you'd have to specify what expression/input you mean. $\endgroup$
    – Jens
    Commented Jul 14, 2015 at 19:55

1 Answer 1

2
$\begingroup$

The key here is to understand the Apply operator. There we want to apply f at level 1 to the list. Therefore, like Guess who it is suggested we can first apply the function f[x, y, z, ##] where ## gets filled in from your list because of the the @@@. Then Total adds up all the functions.

Total[f[x, y, z, ##] & @@@ list]
$\endgroup$
2
  • 1
    $\begingroup$ It is actually f that gets applied to level 1; that is, all the heads at level 1 (List) are changed to f. Total is equivalent to replacing the head at level 0 with Plus. $\endgroup$ Commented Jul 14, 2015 at 21:24
  • $\begingroup$ Thanks for catching this. Answer is updated to reflect your comment. $\endgroup$
    – olliepower
    Commented Jul 14, 2015 at 21:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.