user564376
user564376

Reputation:

Input list to a pure function

The syntax for a pure function is something like (1+#1+#2)&[a,b], which gives 1+a+b. Now I want to supply the output from some function which looks like {a,b} to the function above, i.e., something like (1+#1+#2)&{a,b}, but with the correct syntax, as that obviously doesn't work. How do I go about doing this?

Upvotes: 5

Views: 1310

Answers (3)

Simon
Simon

Reputation: 14731

Here's a version that is an ordinary function (ie can use square brackets) that will take an arbitrary list. The Apply has been moved inside the function and the ## means SlotSequence (c.f. _ and __ in pattern matching)

In[1]:= (1 + ##&@@ #) &[{a, b}]
        (1 + ##&@@ #) &[{a, b, c, d, e}]

Out[1]= 1 + a + b

Out[2]= 1 + a + b + c + d + e

Upvotes: 3

Mr.Wizard
Mr.Wizard

Reputation: 24336

To provide some alternatives, you can also include the Apply within the function if that is more convenient:

f = (1 + # + #2) & @@ # &;

f @ {a, b}
1 + a + b

Optionally, you can index parts manually:

f = (1 + #[[1]] + #[[2]]) &;

Finally, you may already know this, but for others reading this question:

g[{x_, y_}] := 1 + x + y

g @ {a, b}
1 + a + b

Upvotes: 6

Brett Champion
Brett Champion

Reputation: 8577

The easiest approach is to use Apply (@@):

In[4]:= (1 + #1 + #2) & @@ {a, b}

Out[4]= 1 + a + b

Upvotes: 9

Related Questions