0
$\begingroup$

This all the time: an often-recurring coding pattern that is just tedious enough to type and/or just opaque enough, that one feels it should be encapsulated into a function, but at the same time, the amount of code this would require is just too small to warrant creating a package for it (so that one can, in fact, re-use it in the future).

So one just tosses the function in some Misc or Etc package.

Unless, of course, Mathematica already has such a function.

In this case, the pattern-abstracting function would be

singlesToPairs[list_List] := Transpose @ {Drop[list, -1], Drop[list, 1]}

E.g.

singlesToPairs[Range[5]]
(* {{1, 2}, {2, 3}, {3, 4}, {4, 5}} *)

Does Mathematica already have something like this?

$\endgroup$
  • 6
    $\begingroup$ Yes it does, Partition[Range[5], 2, 1]. $\endgroup$ – C. E. Mar 29 '17 at 16:41
2
$\begingroup$

as mentioned by C.E. the preferred built-in function is:

Partition[Range[5], 2, 1]

(* {{1, 2}, {2, 3}, {3, 4}, {4, 5}} *)

as pointed out by Simon Woods:

SequenceCases[Range[5], {_, _}, Overlaps -> True]
(* {{1, 2}, {2, 3}, {3, 4}, {4, 5}} *)

one can also use ReplaceList

ReplaceList[Range[5], {___, a_, b_, ___} :> {a, b}]
(* {{1, 2}, {2, 3}, {3, 4}, {4, 5}} *)

and like your user defined way one can also do it using ReplaceAll in a recursive manner

func[{x_Integer}] := {};
func[x_] := x /. {a_, q_, r___} :> Join[{{a, q}}, func[{q, r}]]

func[Range@5]
(* {{1, 2}, {2, 3}, {3, 4}, {4, 5}} *)

another way

Thread[{Most@#,Rest@#}]&@Range[5]
(* {{1, 2}, {2, 3}, {3, 4}, {4, 5}} *)
$\endgroup$
  • 1
    $\begingroup$ You could also use SequenceCases[Range[5], {_, _}, Overlaps -> True] $\endgroup$ – Simon Woods Mar 29 '17 at 18:09
  • $\begingroup$ @SimonWoods thanks for pointing it out. incorporating your solution. $\endgroup$ – Ali Hashmi Mar 29 '17 at 19:43

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