2
$\begingroup$

I wante to define several functions, all of them with the same arguments, for example:

f[a_, b_, c_]:= ...
g[a_, b_, c_]:= ...
h[a_, b_, c_]:= ...

How can I do this by using something like args = {a,b,c}?

So, having something like

f[arg_]:= ...
g[arg_]:= ...
h[arg_]:= ...
$\endgroup$
  • 1
    $\begingroup$ Welcome to Mathematica.SE! I hope you will become a regular contributor. To get started, 1) 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, 3) remember to accept the answer, if any, that solves your problem, by clicking the checkmark sign, and 4) give help too, by answering questions in your areas of expertise. $\endgroup$ – bbgodfrey Sep 29 '15 at 12:37
9
$\begingroup$

I'm not quite sure what you mean. If you want a way of providing only one argument which then is interpreted as three, you could do:

f[{a_, b_, c_}] := …

f[args_] := With[{a = args[[1]], b = args[[2]], c = args[[3]]}, … ]

fInternal[a_, b_, c_] := …
f[args_] := fInternal[{args}]

or for that last one

f = fInternal @* List;

If you want a way of making sure all three functions receive the same arguments:

args = {x_, y_, z_};

f[args] := x^2 + y^2

f[{1, 2, 3}] (* outputs 5 *)

or

f[Sequence @@ args] := x^2 + y^2

f[1, 2, 3] (* outputs 5 *)
| improve this answer | |
$\endgroup$
  • 2
    $\begingroup$ small improvement to the last approach, you can do args=Sequence@@{x_,y_,z_}, then usage is simply f[args]=.. $\endgroup$ – george2079 Sep 29 '15 at 19:03
  • $\begingroup$ I'm no experienced Mathematica user, but is there any reason why f can't be written like this? f[{x_, y_, z_}] := x^2 + y^2 $\endgroup$ – Ethan Bierlein Sep 29 '15 at 20:23
  • $\begingroup$ @Ethan Yes, that's fine also, but the question is about making it so that we can create several functions with the same signature. The advantage of the second method is that g[args] will immediately have the right arguments. $\endgroup$ – Patrick Stevens Sep 29 '15 at 21:12

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.