Apply list to arguments in Mathematica

How can I apply every item in a list to every argument in a function? A view like Map , with the exception of a variable number of arguments.

So, for example, if I have a function action[x1_,x2_,x3_]:=... , and I have a list {1,2,3} , how would I create a function to call action using action[1,2,3] ?

I would like this function to be able to handle me, changing action to action[x1_,x2] , and everything else, and now the list {1,2} now and now calls the action with action[1,2] .

+8
wolfram-mathematica
source share
3 answers

Based on "View of the same Card, except for a variable number of arguments." I think you can search Apply to level 1. This is done with:

 Apply[function, array, {1}] 

or abbreviation:

 function @@@ array 

Here is what he does:

 array = {{1, 2, 3}, {a, b, c}, {Pi, Sin, Tan}}; action @@@ array 
  {action [1, 2, 3], action [a, b, c], action [Pi, Sin, Tan]} 

The terminology that I used above can be misleading and limits the power of Apply . The expression you apply action to does not have to be a rectangular array. It should not even be List : {...} or have its elements in the form of lists. Here is an example that includes these features:

 args = {1, 2} | f[a, b, c] | {Pi}; action @@@ args 
  action [1, 2] |  action [a, b, c] |  action [Pi] 
  • args not a List , but a collection of Alternatives
  • the number of arguments passed to action changes
  • one of the args elements has head f

Notice, that:

  • action replaces the title of each args element, whatever it is.
  • The head of args saved in the output, in this case Alternatives (short form: a | b | c )
+10
source share
 Apply[action, {1,2,3}] 

This can also be entered as action @@ {1,2,3} .

+8
source share

Why not just use the [lst_? ListQ]?

-2
source share

All Articles