3
$\begingroup$

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

?f

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

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:

?f

f[{a_,b_,c_},x_]:=g@@Evaluate[Append[variables,x]]

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

?f

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

Thanks for any help! Roman

$\endgroup$
3
  • 1
    $\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
    Commented Feb 24, 2015 at 16:38
  • $\begingroup$ something like f[p : Pattern @@@ Thread[{variables, _}], x_] := g[## & @@ p, x]? $\endgroup$
    – kglr
    Commented Feb 24, 2015 at 16:43
  • $\begingroup$ Bill, as g is a compiled function, I cannot evaluate the whole RHS. $\endgroup$
    – Roman
    Commented Feb 24, 2015 at 16:50

2 Answers 2

6
$\begingroup$

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

f[l_, x_] := g[##, x] & @@ l
$\endgroup$
2
  • $\begingroup$ Kuba, yes, much simpler! Thanks a lot. $\endgroup$
    – Roman
    Commented Feb 24, 2015 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
    Commented Feb 24, 2015 at 17:00
4
$\begingroup$

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]))
$\endgroup$

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.