0
$\begingroup$

I have a set of functions which take lists as arguments. They recursively nest sums, and I have defined them as follows

s0[x_, y_] := Total[x] - Total[y]
s1[x_, y_] := 
 Sum[x[[i]] (s0[x[[i + 1 ;; Length[x]]], y]), {i, Length[x]}] - 
  Sum[y[[i]] (s0[{}, y[[i ;; Length[y]]]]), {i, Length[y]}]
s2[x_, y_] := 
 Sum[x[[i]] (s1[x[[i + 1 ;; Length[x]]], y]), {i, Length[x]}] - 
  Sum[y[[i]] (s1[{}, y[[i ;; Length[y]]]]), {i, Length[y]}]

I wish to create a general function Sn which takes the lists x and y as arguments and a third argument n which determines how many times to nest. However when I try the obvious

Sn[n_,x_,y_]:=Sum[x[[i]] (Sn[n-1,x[[i + 1 ;; Length[x]]], y]), {i, Length[x]}] - 
  Sum[y[[i]] (Sn[n-1,{}, y[[i ;; Length[y]]]]), {i, Length[y]}]

The function does not evaluate (it just keeps running). I have tried including a term like

Sn[0,x_,y_]:=s0[x,y]

but this does not seem to have helped matters.

$\endgroup$
  • $\begingroup$ Stackexchange etiquette: If your problem is solved, you should consider accepting the best answer. $\endgroup$ – Philipp Jan 21 '15 at 11:52
0
$\begingroup$

You almost have it right!

sn[n_, x_, y_] := 
   Sum[x[[i]] (sn[n - 1, x[[i + 1 ;; Length[x]]], y]), {i, Length[x]}] - 
    Sum[y[[i]] (sn[n - 1, {}, y[[i ;; Length[y]]]]), {i, Length[y]}];
sn[0, x_, y_] := Total[x] - Total[y]

So for example:

x = RandomReal[{-1, 1}, 10];
y = RandomReal[{-1, 1}, 10];
sn[4, x, y]
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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