9

Given a list of pairs:

data = {{a,b},{c,d},{e,f},{g,h},{i,j}}

I need the moving map:

MapPair[F,data]

{ F[{a,b},{c,d}], F[{c,d},{e,f}], F[{e,f},{g,h}], F[{g,h},{i,j}] }

The built-in function MovingMap does not work:

MovingMap[F,data,2]

Which built-in function does maps a function F pairwise over the data?

QuantumDot
  • 19,601
  • 7
  • 45
  • 121

5 Answers5

14
BlockMap[Apply[F], data, 2, 1]
lericr
  • 27,668
  • 1
  • 18
  • 64
  • i usually use mapthread when i have multiple variables but i knew there had to be a shorter more robust MMA "blackbelt" configuration. i havent tried it but assuming this works this should be at the very top and i definitely be using next time i need to break out with sewing needles. – Jules Manson Jun 10 '22 at 16:55
6

Using MapAt:

MapAt[Apply[F], Partition[data, {2}, 1], All]
(*{F[{a, b}, {c, d}], F[{c, d}, {e, f}], F[{e, f}, {g, h}], F[{g, h}, {i, j}]}*)
E. Chan-López
  • 23,117
  • 3
  • 21
  • 44
3
MapThread[F, {Most@#, Rest@#}]&[data]

(* {F[{a, b}, {c, d}], F[{c, d}, {e, f}], F[{e, f}, {g, h}], F[{g, h}, {i, j}]} *)

In addition, as kglr has pointed out here, Partition can take an undocumented sixth argument.

Partition[data,2,1,{1,-1},{},F]

(* {F[{a, b}, {c, d}], F[{c, d}, {e, f}], F[{e, f}, {g, h}], F[{g, h}, {i, j}]} *)

user1066
  • 17,923
  • 3
  • 31
  • 49
2

2 more possibilities:

data = {{a, b}, {c, d}, {e, f}, {g, h}, {i, j}};

Most @ MapThread[F, {data, RotateLeft @ data}]

{F[{a, b}, {c, d}], F[{c, d}, {e, f}], F[{e, f}, {g, h}], F[{g, h}, {i, j}]}

F @@@ Transpose[{data[[;; -2]], data[[2 ;;]]}]

{F[{a, b}, {c, d}], F[{c, d}, {e, f}], F[{e, f}, {g, h}], F[{g, h}, {i, j}]}

eldo
  • 67,911
  • 5
  • 60
  • 168
2

The first argument of Partition can have any Head. So we can use

List @@ Partition[F @@ data, 2, 1]
{F[{a, b}, {c, d}], 
 F[{c, d}, {e, f}],   
 F[{e, f}, {g, h}],   
 F[{g, h}, {i, j}]}

Generalizing:

partitionMap = List @@ Partition[# @@ #2, ##3] &;

partitionMap[F, data, 2, 1]

{F[{a, b}, {c, d}], 
 F[{c, d}, {e, f}],   
 F[{e, f}, {g, h}],   
 F[{g, h}, {i, j}]}
partitionMap[F, data, 3, 1]
 {F[{a, b}, {c, d}, {e, f}],   
  F[{c, d}, {e, f}, {g, h}],   
  F[{e, f}, {g, h}, {i, j}]}
kglr
  • 394,356
  • 18
  • 477
  • 896