Mathematica Stack Exchange is a question and answer site for users of Mathematica. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I am working with a bunch of functions of the form

fn[x1_,x2_,x3_,...,xn_] := x1x2+x2x3+...+xnx1

where $n$ changes. Is there a way to create these functions efficiently, without having to explicitly define each? I'm looking for a way of declaring, say, $n=5$ and getting back


Perhaps they could be defining iteratively? Since fn and fn-1 only differ by a few monomials. I appreciate any helpo that I can get! Thanks!

share|improve this question

marked as duplicate by Jens, Nasser, Rojo, Mr.Wizard Aug 16 '13 at 18:36

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

up vote 1 down vote accepted

edited to include comment from Kuba

From the manual: "BlankSequence is a pattern object that can stand for any sequence of one or more Mathematica expressions."

f[x__] := (Print["The number of parameters passed is: ", Length[{x}]]; {x}.RotateLeft[{x}])
f[a1, a2, a3]
(*The number of parameters passed is: 3*)
(*a1 a2 + a2 a3*)

Note that you must give a head to that sequence of parameters. In the example above, the calculation of the length of the parameters is not just Length[x] but Length[{x}]. The function you requested is:

f[x__] := {x}.RotateLeft[{x}]
share|improve this answer
You are right, I'll edit the answser. – Hector Aug 16 '13 at 16:19

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