4

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]]
Syed
  • 52,495
  • 4
  • 30
  • 85
thai tran
  • 85
  • 3

2 Answers2

8

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

Function@@{list, expression}
xzczd
  • 65,995
  • 9
  • 163
  • 468
3
$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} *)

Bob Hanlon
  • 157,611
  • 7
  • 77
  • 198