9

How would I go about applying each element in a list to each argument in a function? Kind of like Map, except with 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 with action[1,2,3]?

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

3 Answers 3

11

Based on "Kind of like Map, except with a variable number of arguments." I think you might be looking for Apply to level 1. This is done with:

Apply[function, array, {1}]

or the shorthand:

function @@@ array

Here is what it 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 I used above could be misleading, and limits the power of Apply. The expression to which you apply action does not need to be a rectangular array. It does not even need to be a List: {...} or have its elements be lists. Here is an example incorporating these possibilities:

args = {1, 2} | f[a, b, c] | {Pi};

action @@@ args
   action[1, 2] | action[a, b, c] | action[Pi] 
  • args is not a List but a set of Alternatives
  • the number of arguments passed to action varies
  • one of the elements of args has head f

Observe that:

  • action replaces the head of each element of args, whatever it may be.
  • The head of args is preserved in the output, in this case Alternatives (short form: a | b | c)
Sign up to request clarification or add additional context in comments.

2 Comments

what is the difference between your solution and Sasha's? I mean, I see @@@ in yours and only @@ in his. How can they both be the same?
@d'o-o'b they are not the same, but they are for the same function: Apply. f @@ {1,2,3} gives f[1,2,3] in effect replacing List with f at "Level 0" (the top level of {1,2,3}). By contrast, f @@@ {{1}, {2}, {3}} gives {f[1], f[2], f[3]}, replacing List with f for each element of the list, or "Level 1." This can also be done for deeper levels of an expression using Apply[f, expression, levelspec] but there is no shorthand (like @@ or @@@) for this. See the help on Level for details of levelspec.
9
Apply[action, {1,2,3}]

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

Comments

-2

Why not just use action[lst_?ListQ]?

1 Comment

Is this the question you meant to answer?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.