Re: Variable number of arguments
- To: mathgroup at smc.vnet.net
- Subject: [mg113342] Re: Variable number of arguments
- From: Bob Hanlon <hanlonr at cox.net>
- Date: Sun, 24 Oct 2010 06:06:15 -0400 (EDT)
It's not clear what you want done if the multiple elements are themselves lists or the arguments are a mix of lists and individual elements. The following approach will sum all the individual elements no matter how they are structured.
funnySum1[x__] := Plus @@ Flatten[{x}]
{funnySum1[1, 2, 3, 4],
funnySum1[{1, 2, 3, 4}],
funnySum1[1, 2, {3, 4}],
funnySum1[{1, 2}, {3, 4}],
funnySum1[{{1, 2}, {3, 4}}]}
{10, 10, 10, 10, 10}
funnySum2[x__] := Total[Flatten[{x}]]
{funnySum2[1, 2, 3, 4],
funnySum2[{1, 2, 3, 4}],
funnySum2[1, 2, {3, 4}],
funnySum2[{1, 2}, {3, 4}],
funnySum2[{{1, 2}, {3, 4}}]}
{10, 10, 10, 10, 10}
funnySum3[x__] := Tr[Flatten[{x}]]
{funnySum3[1, 2, 3, 4],
funnySum3[{1, 2, 3, 4}],
funnySum3[1, 2, {3, 4}],
funnySum3[{1, 2}, {3, 4}],
funnySum3[{{1, 2}, {3, 4}}]}
{10, 10, 10, 10, 10}
Bob Hanlon
---- Sam Takoy <sam.takoy at yahoo.com> wrote:
=============
Hi,
I'm looking for help writing functions with variable number of arguments.
For example, how do I accomplish the (rather artificial) task of writing
the function FunnySum that:
- When called with multiple arguments, sums them
- When called with a list, sums the elements of the list
I was hoping that the FunnySum1 below would work, but it doesn't
multiple arguments. FunnySum2 works, but is that the best solution?
FunnySum1[k__] := Apply[Plus, If[ListQ[k], Sequence[k], k]]
FunnySum1[{1, 2, 3, 4, 5, 6}]
FunnySum2[k__] := Plus[k]
FunnySum2[k_List] := Apply[Plus, Sequence[k]]
FunnySum2[1, 2, 3, 4, 5, 6]
FunnySum2[{1, 2, 3, 4, 5, 6}]
Many thanks in advance,
Sam