4

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.

thai tran
  • 85
  • 3

4 Answers4

4

Use the resource function TensorPureFunction:

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

f[listin][[1]]

(48)

E. Chan-López
  • 23,117
  • 3
  • 21
  • 44
4

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 *)

user1066
  • 17,923
  • 3
  • 31
  • 49
3
$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 *)

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

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

lericr
  • 27,668
  • 1
  • 18
  • 64