given a list of variables

variables = {a, b, c};

I want to automatically define a function

f[{a_,b_,c_},x_] := g[a,b,c,x]

(I do need a delayed assignment here, since g is a compiled function).

As a first attempt I define

f[Evaluate[Pattern[#,Blank[]]&/@variables], x_] := Evaluate[Append[variables, x]]

which works out as



This is good so far.

As a next step I want to pass the parameter list to the function g:

f[Evaluate[Pattern[#,Blank[]]&/@variables], x_] := g @@ Evaluate[Append[variables, x]]

This does not work, as the argument list for g is now left unevaluated:



What do I need to change in my definition of f in order to get



Thanks for any help! Roman

  • $\begingroup$ Welcome to Mathematica.SE! I suggest that: 1) You take the introductory Tour now! 2) When you see good questions and answers, vote them up by clicking the gray triangles, because the credibility of the system is based on the reputation gained by users sharing their knowledge. Also, please remember to accept the answer, if any, that solves your problem, by clicking the checkmark sign! 3) As you receive help, try to give it too, by answering questions in your area of expertise. $\endgroup$ – bbgodfrey Feb 24 '15 at 16:38
  • $\begingroup$ something like f[p : Pattern @@@ Thread[{variables, _}], x_] := g[## & @@ p, x]? $\endgroup$ – kglr Feb 24 '15 at 16:43
  • $\begingroup$ Bill, as g is a compiled function, I cannot evaluate the whole RHS. $\endgroup$ – Roman Feb 24 '15 at 16:50

I think this approach is an overreaction. Maybe something like this will be ok?

f[l_, x_] := g[##, x] & @@ l
| improve this answer | |
  • $\begingroup$ Kuba, yes, much simpler! Thanks a lot. $\endgroup$ – Roman Feb 24 '15 at 16:59
  • $\begingroup$ kguler, naming the pattern is a good idea. But in this case I think Kuba's solution is simpler, by avoiding naming of the individual components of the parameter list at all. $\endgroup$ – Roman Feb 24 '15 at 17:00

While Kuba's answer is simpler, what you asked for can be accomplished also rather easily with the help of the nested injector pattern:

variables /. {vars__} :> 
    (Map[Pattern[#, Blank[]] &, {vars}] /. {patts__} :>  
         (f[{patts}, x_] := g[vars, x]))
| improve this answer | |

Your Answer

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

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