# How to ask Mathematica to do the given operation for a set of parameters?

I have a set of numbers like this

 s = {a, b, c, d, e, f, ..., g, h}

and I would like to ask Mathematica to do the following operation (to sum the subtractions of adjacent numbers)

 (a - b) + (c - d) + (e - f) + ... + (g - h)

Is it possible to do that?

• s[[;; ;; 2]] - s[[2 ;; ;; 2]] // Total? Assumes the length is even Apr 27, 2021 at 23:28
• @MichaelE2 Thank you very very much :), yes, it works.
– user67849
Apr 27, 2021 at 23:33

Some more options

Clear[a, b, c, d, e, f, g, h];
s = {a, b, c, d, e, f, g, h};

Total[Table[s[[n]] - s[[n + 1]], {n, 1, Length[s] - 1, 2}]]

Sum[s[[n]] - s[[n + 1]], {n, 1, Length[s] - 1, 2}]

Total[SequenceCases[s, {j_, k_} :> j - k]]

Total[Subtract @@@ Partition[s, 2]]


All give

a - b + c - d + e - f + g - h

A mathematical approach: $$\sum_{k=1}^n (-1)^{k+1} s_k$$ translates as follows

s = {a, b, c, d, e, f, g, h};
Sum[(-1)^(k+1) s[[k]], {k, 1, Length[s]}]
(* a - b + c - d + e - f + g - h *)

☺ = +## & @@ (#[[;; ;; 2]] - #[[2;; ;; 2]]) &;

☺ @ {a, b, c, d, e, f, g, h}

 a - b + c - d + e - f + g - h