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: [mg113333] Re: Variable number of arguments
  • From: Bill Rowe <readnews at sbcglobal.net>
  • Date: Sun, 24 Oct 2010 06:04:34 -0400 (EDT)

On 10/23/10 at 7:04 AM, sam.takoy at yahoo.com (Sam Takoy) wrote:

>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}]

What is "best"? Here is another way that is at least a simpler definition

In[1]:= f[x__] := Plus @@ Flatten[{x}]

In[2]:= f[{1, 2, 3}]

Out[2]= 6

In[3]:= f[1, 2, 2]

Out[3]= 5

In[4]:= f[1, {2, 3}, 4]

Out[4]= 10

or perhaps,

In[8]:= g[k__] := Plus[k]

In[9]:= g[k_List] := Plus @@ k

In[10]:= g[1, 2, 3]

Out[10]= 6

In[11]:= g[{1, 2, 3}]

Out[11]= 6

In[12]:= g[1, {2, 3}, 3]

Out[12]= {6,7}



  • Prev by Date: Re: Variable number of arguments
  • Next by Date: fyi, A nice package for making plot ticks
  • Previous by thread: Re: Variable number of arguments
  • Next by thread: Re: Variable number of arguments