Possible Duplicate:
How to create functions of arbitrary number of variables?

i want to use a Function f[] with different set of arguments. example: f[{x,y,z}] as well as f[{x1,y1,z1},{x2,y2,z2},...,{xn,yn,zn}]. How do i write its definition to accept Both type of calls.


2 Answers 2


The pattern matching in Mathematica gives you a powerful way to define recursive functions.

For example if you'd like to write a function which takes a Mathematica function definition and generates C-Code from it:

<< SymbolicC`
SetAttributes[toSymbolicC, {HoldAll}]
toSymbolicC[x_List] := toSymbolicC /@ x
toSymbolicC[(op : (Plus | Times))[args___]] := 
           COperator[op, toSymbolicC[{args}]]
toSymbolicC[(op : (Cos | Sin))[x_]] := 
           CStandardMathOperator[op, toSymbolicC[x]]
toSymbolicC[x_] := x

I know this should be more elaborated but for the sake brevity I just defined functions for lists, two commutative operators, Cos and his imaginary friend ;).

You'd use it in that way:

toSymbolicC[Cos[x] + Sin[x]]

which yields:

COperator[Plus, {CStandardMathOperator[Cos, x], CStandardMathOperator[Sin, x]}]

to convert this into a regular C-Expression you'd use (of course you could've done this in postfix form)


Hope this gave an idea about the power of pattern matching, especially in symbolic programming languages like Mathematica.

Patterns in Mathematica


You simply write them:

f[{x_,y_,z_}]:= definition1
f[{x_,y_,z_},{x1_,y1_,z1_},{x2_,y2_,z2_}]:= definition2

Of if you want to match this pattern one or more times you can use the Repeated pattern operator .., and bind the sequence of matches to a single variable p:

f[p:({_,_,_}..)] := definition3

Mathematica will use the most specific pattern that matches a call.

  • $\begingroup$ @jVincentMy definitions of f[] depend on number of Arguments, How do i know how many arguments have been passed ? $\endgroup$
    – santhosh
    Dec 19, 2012 at 10:11
  • $\begingroup$ @user4972 In the above you know for certain that definition 1 has one passed, and definition 2 has three passed. In the last definition, the matched p be equal to Sequence[{x,y,z},{x1,y1,z1},...,{xN,yN,zN}], so you can find the length using Length[{p}]. Note that {} is needed due to the way Sequence works. $\endgroup$
    – jVincent
    Dec 19, 2012 at 10:15
  • $\begingroup$ So instead Of 1st 2 definitions, i can directly use last one and use Length[{p}] for number of times to execute my operations right ? $\endgroup$
    – santhosh
    Dec 19, 2012 at 10:26
  • $\begingroup$ @user4972 Yes, the first two examples where to highlight how you would go about if you knew exactly what numbers it should work for. $\endgroup$
    – jVincent
    Dec 19, 2012 at 10:58
  • $\begingroup$ okay.And how do i identify each set of arguments and work on them ? Can i find it like p[[i]] till length[{p}] ? $\endgroup$
    – santhosh
    Dec 19, 2012 at 11:46

Not the answer you're looking for? Browse other questions tagged or ask your own question.