Services & Resources / Wolfram Forums / MathGroup Archive
-----

MathGroup Archive 2010

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: Variable number of arguments

  • To: mathgroup at smc.vnet.net
  • Subject: [mg113340] Re: Variable number of arguments
  • From: Peter Breitfeld <phbrf at t-online.de>
  • Date: Sun, 24 Oct 2010 06:05:52 -0400 (EDT)
  • References: <i9ufg6$rgc$1@smc.vnet.net>

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
>

It's enough to do the following:

funnysum[x__]:=Plus[x]
funnysum[x_List]:=funnysum[Sequence @@ x]


-- 
_________________________________________________________________
Peter Breitfeld, Bad Saulgau, Germany -- http://www.pBreitfeld.de


  • Prev by Date: Re: palettes that would not move
  • Next by Date: Re: Variable number of arguments
  • Previous by thread: Re: Variable number of arguments
  • Next by thread: Re: Variable number of arguments