Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing parameters stored in a list to expression

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.

like image 414
hellboy198x Avatar asked Nov 30 '22 08:11

hellboy198x


2 Answers

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

like image 37
Brett Champion Avatar answered Dec 05 '22 06:12

Brett Champion


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.

like image 187
rcollyer Avatar answered Dec 05 '22 04:12

rcollyer