I have a list of arguments (which in reality is lengthy):
arguments = {a, b, c}
arguments2 = {a_, b_, c_}
f[Sequence@@arguments2] := a + b + c
Note: It seems awkward to define two lists here, there should be a better way to do this.
And I want to numerically integrate a function of those arguments:
int[Sequence@@arguments2] := NIntegrate[f[Sequence@@arguments], {x, 0, 1}]
This does not work because of the HoldAll
property of NIntegrate
.
Is there a way to do this correctly?
Answer
If your question is a duplicate of Injecting a sequence of expressions into a held expression the simplest solution is the same, the so-called "injector pattern":
{a, b, c} /. _[args__] :> NIntegrate[f[args], {x, 0, 1}]
NIntegrate[f[a, b, c], {x, 0, 1}]
I did not close this as a duplicate however because it seems you would like to approach this problem differently.
You could store your symbols in a single object, e.g.:
syms = Hold[a, b, c];
Then create the Pattern
sequence from these:
toPatSeq = ReleaseHold @ Quiet @ Replace[#, x_ :> x_, {1}] &;
toPatSeq @ syms
Sequence[a_, b_, c_]
Now you could define your function with:
syms /. _[args__] :>
(int[toPatSeq @ syms] := NIntegrate[f[args], {x, 0, 1}])
Check:
? int
Global`int
int[a_,b_,c_]:=NIntegrate[f[a,b,c],{x,0,1}]
This works even if the symbols a
, b
, c
, have values assigned.
If as this example shows you only want an arbitrary sequence of symbols you could also make use of Unique
:
syms = Hold @@ Table[Unique[], {3}];
syms /. _[args__] :>
(int[toPatSeq @ syms] := NIntegrate[f[args], {x, 0, 1}])
?int
Global`int
int[$1_,$2_,$3_]:=NIntegrate[f[$1,$2,$3],{x,0,1}]
Comments
Post a Comment