6
$\begingroup$

I have a list of integers and want to create a list of releation where each integer relates to the next one in the list. (no wrap-around). That is, I want to transform

{1, 2, 3, 4}

to

{1 -> 2, 2 -> 3, 3 -> 4}

I tried to replace the expression in the following way:

{1, 2, 3, 4} //. {x___, a_?NumberQ, b_?NumberQ, y___} :> {x, a -> b, y}

but that doesn't give the right result.

$\endgroup$
  • 11
    $\begingroup$ Rule @@@ Partition[{1, 2, 3, 4}, 2, 1] $\endgroup$ – corey979 Jan 3 '17 at 23:26
  • $\begingroup$ Teeny modification: Rule @@@ Partition[Range[4], 2,1] $\endgroup$ – David G. Stork Jan 4 '17 at 0:39
10
$\begingroup$

corey979 already gave the standard solution in the comments:

Rule @@@ Partition[{1, 2, 3, 4}, 2, 1]

{1 -> 2, 2 -> 3, 3 -> 4}

But this is also doable with rules like you tried. I'd do it like this:

{1, 2, 3, 4} //. {
  {a___, x_Integer, y_Integer, b___} :> {a, x -> y, y, b},
  {rules___Rule, _Integer} :> {rules}
  }

{1 -> 2, 2 -> 3, 3 -> 4}

$\endgroup$
10
$\begingroup$

BlockMap:

BlockMap[Apply@Rule, Range@4, 2, 1]

(* {1 -> 2, 2 -> 3, 3 -> 4} *)
$\endgroup$
3
$\begingroup$

Using Through, which I'm always looking for a reason to use, and rarely find one:

(Most -> Rest)@{1, 2, 3, 4} // Through // Thread

(* {1 -> 2, 2 -> 3, 3 -> 4} *)
$\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.