# Change format of vector for input argument of function

I have a function f defined as

list = {a1, a2, a3, a4, a5, a6};
expression = a1 + a2^2 + a3^2 + a4 + a5*a6;
f = Function @@ {list, expression};


The input in vector is something likes

listin = {1, 2, 3, 4, 5, 6};


but when using

f[listin]


it informs error:"Too many parameters in {a1,a2,a3,a4,a5,a6} to be filled from \Function[{a1,a2,a3,a4,a5,a6},a1+a2^2+a3^2+a4+a5\ a6][{1,2,3,4,5,6}]".

I wonder is there any way to change format of the listin to make it works.

\$Version

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

Clear["Global*"]

list = {a1, a2, a3, a4, a5, a6};
expression = a1 + a2^2 + a3^2 + a4 + a5*a6;
f = Function @@ {list, expression};

listin = {1, 2, 3, 4, 5, 6};


The argument to f is a sequence, so you need to Apply (@@) the function f

f @@ listin

(* 48 *)


Alternatively, convert the input to a Sequence

f[Sequence @@ listin]

(* 48 *)


Use the resource function TensorPureFunction:

f = ResourceFunction["TensorPureFunction"][{expression}][{list}]

f[listin][[1]]

(*48*)


Personally I would use Apply as Bob Hanlon has shown in his answer.

But just for fun:

ReplaceAt[listin, List->f,0]

(* 48 *)


Or:

ReplaceAt[listin, List->ReplaceAt[{list,expression}, List->Function,0],0]

(* 48 *)


But, as shown in previous neat answers (here and here), the above is equivalent to the following:

(Function@@{list,expression})@@listin

(* 48 *)


Or:

g={list,expression};g[[0]]=Function;

g@@listin

(* 48 *)


Or (! modification in place):

ClearAll[gg]

gg={list,expression};gg[[0]]=Function;
x=listin;x[[0]]=gg;
gg//OutputForm
x

(*
Function[{a1, a2, a3, a4, a5, a6}, a1 + a2^2  + a3^2  + a4 + a5 a6]
48
*)

• (+1) I had already seen this use of ReplaceAt in another answer of yours, I find it very useful. Commented Apr 7, 2023 at 18:21

If you have an expression,

a1 + a2^2 + a3^2 + a4 + a5*a6


that you want to be the body of a function, and you also know the exact order of the arguments to that function, in your case given by

list = {a1, a2, a3, a4, a5, a6}


, then why are you going through the trouble to force these argument names into your function definition? You could just as easily do this:

f = Function[Null, #1 + #2^2 + #3^2 + #4 + #5 #6]


To demonstrate:

f @@ list


a1 + a2^2 + a3^2 + a4 + a5 a6

list = {a1, a2, a3, a4, a5, a6};

expr = a1 + a2^2 + a3^2 + a4 + a5 * a6;


Using ReplaceAll

expr /. Thread[list -> Range[Length @ list]]


48

Using Variables (no need for list)

ReplaceAll[expr, Thread[# -> Range[Length @ #]]] & @ Variables[expr]
`

48