Re: Variable number of arguments

*To*: mathgroup at smc.vnet.net*Subject*: [mg113341] Re: Variable number of arguments*From*: Andy <andyr at wolfram.com>*Date*: Sun, 24 Oct 2010 06:06:03 -0400 (EDT)

On 10/23/2010 6:04 AM, Sam Takoy 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 > You could use FunnySum1[k__] := Apply[Plus, Sequence @@@ {k}] If you want to ignore list structure altogether so that things like FunnySum1[{1, {2,3},4},5] would give 15 you would need to use Apply[ Plus, Flatten[ { k } ] ] instead. -Andy