Function with different set of arguments [duplicate]

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.

-

marked as duplicate by Jens, whuber, rcollyer, Yves Klett, ArtesDec 20 '12 at 14:45

This could be considered a duplicate of How to create functions of arbitrary number of variables? –  Jens Dec 19 '12 at 18:47

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
ClearAll[toSymbolicC]
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)

ToCCodeString[%]


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.

-
@jVincentMy definitions of f[] depend on number of Arguments, How do i know how many arguments have been passed ? –  santhosh Dec 19 '12 at 10:11
@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. –  jVincent Dec 19 '12 at 10:15
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 ? –  santhosh Dec 19 '12 at 10:26
@user4972 Yes, the first two examples where to highlight how you would go about if you knew exactly what numbers it should work for. –  jVincent Dec 19 '12 at 10:58
okay.And how do i identify each set of arguments and work on them ? Can i find it like p[[i]] till length[{p}] ? –  santhosh Dec 19 '12 at 11:46