Skip to main content
2 of 2
Added a more general case
Leonid Shifrin
  • 114.9k
  • 16
  • 333
  • 424

Here is one way:

movingMapCircular[f_, l_List] := MapThread[f@* List, {l, RotateLeft[l]}];

For example:

movingMapCircular[f, {1, 2, 3, 4}]

(* {f[{1, 2}], f[{2, 3}], f[{3, 4}], f[{4, 1}]} *)

A generalization of this approach for arbitrary window size may look like:

ClearAll[movingMapCircular];
movingMapCircular[f_, l_List, {n_Integer}] :=
  MapThread[
    f@* List,
    MapThread[RotateLeft, {ConstantArray[l, n], Range[0, n - 1]}]
  ];

for example:

movingMapCircular[f, Range[5], {3}]

(* {f[{1, 2, 3}], f[{2, 3, 4}], f[{3, 4, 5}], f[{4, 5, 1}], f[{5, 1, 2}]} *)
Leonid Shifrin
  • 114.9k
  • 16
  • 333
  • 424