This might be a very basic question, so apologies in advance, but I couldn't find a direct solution.

Suppose I have a module that takes function(s) and expression(s) as its arguments. For the sake of brevity, let's say it's a one-liner

testModule[{func0_, a0_}] :=  Module[{func = func0, a = a0}, Integrate[func[x, a], {x, -1, 1}]]

and I want to create a list of testModule outputs for a bunch of choices of arguments. I can brute-force this by explicitly defining the functions and then a vector of arguments for testModule, say,

f1[x_, a_] := a^2 + x^2
f2[x_, a_] := a - x
f3[x_, a_] := a + x
f4[x_, a_] := Exp[a*x]
vFunctions = {{f1, 1}, {f2, 2}, {f3, 1}, {f4, a}}

and get the result I want with

Table[testModule[vFunctions[[i]]], {i, 1, Length[vFunctions]}]

However, let's say that, for some reason, it's easier for me to construct the argument array with just expressions, keeping in mind that (with the example module from above) it's implied that in each element of the vector, the first element of each element is supposed to be a function

vExpressions =  Transpose[{{a^2 + x^2, a - x, a + x, Exp[a*x]}, {1, 2, 1, a}}]

Can I construct the table by turning the expressions into functions when calling testModule? Something like

Table[testModule[{With[{func0[x_, a_] := vExpressions[[i]][[1]]}, func0], vExpressions[[i]][[2]]}], {i, 1, Length[vExpressions]}]

does not work (because With only allows assigning symbols,

With::lvset: Local variable specification {func0[x_,a_]:=vExpressions[[i]][[1]]} contains func0[x_,a_]:=vExpressions[[i]][[1]], which is an assignment to func0[x_,a_]; only assignments to symbols are allowed.

and so on), and I couldn't come up with a different way of doing this. Is there a way to achieve something like this, or is it just a bad idea?

  • $\begingroup$ What you want to do can be dangerous. What guarantee do you have that, say, x, does not have a value previously assigned to it before you evaluate all of this? $\endgroup$ – J. M. is away Mar 7 '18 at 13:04
  • $\begingroup$ You can turn an expression into a function using Function and the Inactive-framework. E.g. Activate[Inactive[Function][{x, a}, expr]] for any expression involving x and a. You may want to check that neither x nor a have values assigned, using ValueQ[x] etc. $\endgroup$ – JEM_Mosig Mar 7 '18 at 21:58
  • $\begingroup$ @JEM_Mosig ah, I've never seen that before, it seems incredibly handy, thank you so much! It does exactly what I wanted. And yes, I'll make sure x,a are unassigned, although for the particular calculation I'm doing I think it's always going to be the case. $\endgroup$ – starless Mar 8 '18 at 9:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.