4
$\begingroup$

I want to pass a list of input arguments to a function. Something like:

list = {a1, a2, a3};
expression = a1 + a2^2 + a3^2;
f = Function[list, Evaluate[expression]];

and f[1,2,3] must evaluate to 14. Is there any way to use the list for f instead of using

f = Function[{a1,a2,a3}, Evaluate[expression]]
$\endgroup$
1
  • 4
    $\begingroup$ f[a_, b_, c_] := a + b^2 + c^2 $\endgroup$
    – lericr
    Apr 6, 2023 at 23:27

2 Answers 2

8
$\begingroup$

I won't be surprised if this is a duplicate, but it's easier for me to write an answer:

Function@@{list, expression}
$\endgroup$
3
$\begingroup$
$Version

(* "13.2.1 for Mac OS X ARM (64-bit) (January 27, 2023)" *)

Clear["Global`*"]

For the argument to be either a list or a sequence

f[x__ /; (Length[Flatten[{x}]] == 3)] := Total[Flatten[{x}]^{1, 2, 2}]

For example,

{f[{a1, a2, a3}], f[{1, 2, 3}], f[a1, a2, a3], f[1, 2, 3]}

(* {a1 + a2^2 + a3^2, 14, a1 + a2^2 + a3^2, 14} *)
$\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.