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.
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[] and Evaluate[f]
is used to turn the function into Function[{a,b}, a^2+b^2]
)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With