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.
3 Answers
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.
A couple other ways...
Use rule replacement
f /. Thread[{a,b} -> l]
(where
Thread[{a,b} -> l]
will evaluate into{a->1, b->2}
)Use a pure function
Function[{a,b}, Evaluate[f]] @@ l
(where
@@
is a form of Apply[] andEvaluate[f]
is used to turn the function intoFunction[{a,b}, a^2+b^2]
)

- 8,497
- 1
- 27
- 44
-
Yeah. We could write a blog: The 1001 ways to get the `SquaredEuclideanDistance[ ]` without mentioning it. :D – Dr. belisarius Mar 03 '11 at 04:03
-
I avoided mentioning Dot[l,l] b/c I figured it was a bit too tuned to the specifics of the question... – Brett Champion Mar 03 '11 at 04:18
-
@Brett See my answer. I wasn't ashamed to suggest `l.l` :D – Dr. belisarius Mar 03 '11 at 04:27
-
@Belisarius Why'd you leave out `z = Complex @@ l;z*Conjugate[z]`? (And if we get to 1001, do we win a prize, or get kicked out?) :-) – Brett Champion Mar 03 '11 at 04:42
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;

- 60,527
- 15
- 115
- 190