5

How can I pass values to a given expression with several variables? The values for these variables are placed in a list that needs to be passed into the expression.

Abhinav
  • 268
  • 1
  • 7
  • 19
hellboy198x
  • 71
  • 1
  • 4

3 Answers3

15

Your revised question is straightforward, simply

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

where @@ is shorthand for Apply. Internally, {a,b,c} is List[a,b,c] (which you can see by using FullForm on any expression), and Apply just replaces the Head, List, with a new Head, f, changing the function. The operation of Apply is not limited to lists, in general

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

Also, look at Sequence which does

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

So, we could do this instead

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

which while pedantic seeming can be very useful.

Edit: Apply has an optional 2nd argument that specifies a level, i.e.

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

Note: the shorthand for Apply[fcn, expr,{1}] is @@@, as discussed here, but to specify any other level description you need to use the full function form.

Community
  • 1
  • 1
rcollyer
  • 10,475
  • 4
  • 48
  • 75
4

A couple other ways...

  1. Use rule replacement

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

    (where Thread[{a,b} -> l] will evaluate into {a->1, b->2})

  2. Use a pure function

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

    (where @@ is a form of Apply[] and Evaluate[f] is used to turn the function into Function[{a,b}, a^2+b^2])

Brett Champion
  • 8,497
  • 1
  • 27
  • 44
3

For example, for two elements

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

for any number of elements

g[l_List] := l.l

or

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

So:

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

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

Two more, just for fun:

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

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

Edit

Regarding your definition

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

It has a few problems:

1) You are defining a constant, because the a,b are not parameters.
2) You are defining a function with Set, Instead of SetDelayed, so the evaluation is done immediately. Just try for example

 s[l_List] = Total[l]

vs. the right way:

 s[l_List] := Total[l]  

which remains unevaluated until you use it.

3) You are using a pattern without a name {__} so you can't use it in the right side of the expression. The right way could be:

f[{a_,b_}]:= a^2+b^2;
Dr. belisarius
  • 60,527
  • 15
  • 115
  • 190