Passing parameters stored in a list to an expression

How to pass values ​​to a given expression with multiple variables? The values ​​for these variables are placed in the list that must be passed to the expression.

+4
source share
3 answers

Your revised question is simple, simple

f @@ {a,b,c,...} == f[a,b,c,...]

where @@is the abbreviation for Apply. Inside {a,b,c}there List[a,b,c](you can see, using FullFormfor any expression), and Applysimply replaces Head, Listwith a new Head, fwhich changes the function. The operation is Applynot limited to lists, in general

f @@ g[a,b] == f[a,b]

Also, look Sequencewho does

f[Sequence[a,b]] == f[a,b]

So, we could do it instead

f[ Sequence @@ {a,b}] == f[a,b]

, , .

: Apply 2 nd , ..

Apply[f, {{a,b},{c,d}}, {1}] == {f[a,b], f[c,d]}

. Apply[fcn, expr,{1}] @@@, , .

+12

...

  • f /. Thread[{a,b} -> l]

    ( Thread[{a,b} -> l] {a->1, b->2})

  • Function[{a,b}, Evaluate[f]] @@ l

    ( @@ Apply [] Evaluate[f] Function[{a,b}, a^2+b^2])

+4

,

f[l_List]:=l[[1]]^2+l[[2]]^2  

g[l_List] := l.l

h[l_List]:= Norm[l]^2

:

Print[{f[{a, b}], g[{a, b}], h[{a, b}]}]

{a^2 + b^2, a^2 + b^2, Abs[a]^2 + Abs[b]^2}  

, :

i[l_List] := Total@Table[j^2, {j, l}]

j[l_List] := SquaredEuclideanDistance[l, ConstantArray[0, Length[l]]  

f[{__}] = a ^ 2 + b ^ 2;  

:

1) You define a constant because you a,bare not parameters.
2) You define a function using Set, not SetDelayed, so evaluation is done immediately. Try for example

 s[l_List] = Total[l]

against. the right way:

 s[l_List] := Total[l]  

which remains unsatisfactory until you use it.

3) You use a template without a name {__}so that you cannot use it on the right side of the expression. The right way:

f[{a_,b_}]:= a^2+b^2;
+3
source

All Articles