MathGroup Archive 2010

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

Search the Archive

Variable number of arguments

  • To: mathgroup at
  • Subject: [mg113307] Variable number of arguments
  • From: Sam Takoy <sam.takoy at>
  • Date: Sat, 23 Oct 2010 07:04:44 -0400 (EDT)


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,


  • Prev by Date: Re: Replacement in a held function
  • Next by Date: Re: Two questions related to Arrays
  • Previous by thread: Color Function example?
  • Next by thread: Re: Variable number of arguments