# Writing a function with variable arguments [duplicate]

I want to write a function which takes multiple arguments varying from 1 to n, where each argument is a triplet.

sublistProduct[{$a_1,b_1,c_1$},{$a_2,b_2,c_2$},...] = { $\Pi_{i=1}^{i=n}a_i ,\Pi_{i=1}^{i=n} b_i,\forall i \;\;max(c_i)$}

For example sublistProduct[{1,2,3},{2,3,3},{3,4,5}] = {6,24,5} There can be any number of inputs(triplets) to the functions

• Related or possible duplicates: (6588), (15749), (26686) Apr 8 '15 at 15:06
• @Mr.Wizard definitely related. BTW, how do you keep track of all your answers? :) Apr 8 '15 at 15:17
• @rcollyer For a while I was keeping a list, not only of my posts but any that were frequent duplicates, but recently I've just been using search which I seem to be getting better with. However since I remember my own wording or style better than I recall others I seem to find more of my own answers. I encourage you to link any I miss as you are able. By the way I just added two more links; I think at least one of these is a duplicate. Please vote if you agree. Apr 8 '15 at 15:20
• @rcollyer Oops, one of those links was not a duplicate; I remembered it wrong. See, I don't keep track very well. ;-p Apr 8 '15 at 15:23
• @Mr.Wizard I was the first vote. Apr 8 '15 at 16:04

The key is in defining the pattern correctly. I would use something like this:

Clear[f]
f[terms : {_, _, _} ..] := terms


which when used does this

f[{1,2,3}]
(* {1,2,3} *)
f[{1,2,3}, {2,3,4}]
(* Sequence[{1,2,3}, {2,3,4}] *)


So, to make effective use of that pattern, I would then put it into a list, e.g.

Clear[f]
f[terms : {_, _, _} ..] := {terms}


so that I can manipulate it at will. For instance,

Clear[f]
sublistProduct[terms : {_, _, _} ..] :=
{Times@@#1, Times@@#2, Max@#3}& @@ Transpose[{terms}]

• This just creates clubbed list of terms in the first and second position of the triplet. Like sublistProduct[{1,2,2},{2,3,4}] = {{1,2},{2,3},4} Apr 10 '15 at 7:16
• TImes function doesn't work on lists. Is there a method to remove the brackets from a list, when passing it to a function? Apr 10 '15 at 7:33
• It worked, Just had to add another function Times2[{a__}]:= Times[a].. Thanks for the answer. I would have accepted it, had you included this also. Apr 10 '15 at 8:55
• Better yet, just replace Times@ with Times@@ Apr 10 '15 at 9:56
• @LLlAMnYP yes, that's a mistake in my answer. Fixing now. Apr 10 '15 at 17:41

Use BlankSequence in function definition, e.g. to get a list of all the first elements:

f[triplets__] := {triplets}[[All, 1]]


so you can use it as

f[{a1, b1, c1}, {a2, b2, c2}]
(* {a1, a2} *)


Note that this doesn't actually restrict you to using triplets as arguments for f, just that you have to give it one or more arguments.