3

I want a list like this:

{x :> Print[1], x :> Print[2], x :> Print[3], x :> Print[4], x :> Print[5]}

I tried:

Table[x :> Print[i], {i, 5}]

But it gives:

{x :> Print[i], x :> Print[i], x :> Print[i], x :> Print[i], x :> Print[i]}

It seems that you can't iterate things on the right hand side of delayed rules. Is there a easy way to do this?

xzhu
  • 704
  • 4
  • 9

2 Answers2

5

This question is answered elsewhere, but to get some ink on the page until I can link the duplicate here is a CW answer.

I would use Array:

Array[(x :> Print[#]) &, 5]
{x :> Print[1], x :> Print[2], x :> Print[3], x :> Print[4], x :> Print[5]}

Other methods using Table:

Table[With[{n = i}, x :> Print[n]], {i, 5}]

Table[(x :> Print[n]) /. n -> i, {i, 5}]

Table[i /. n_ :> (x :> Print[n]), {i, 5}]

Table[(x :> Print[#]) &[i], {i, 5}]

Contrived ways for amusement if nothing else:

MapAt[Print, RuleDelayed @@@ Thread[x -> Range[5]], {All, 2}]

Table[Hold[RuleDelayed][x, Hold[Print][i]], {i, 5}] // ReleaseHold

Table[x -> p[i], {i, 5}] /. {p -> Print, Rule -> RuleDelayed}

List @@ Thread[x :> Evaluate[Print /@ Hold @@ Range@5], Hold]
Mr.Wizard
  • 271,378
  • 34
  • 587
  • 1,371
0
ToExpression@
 Table["x \[RuleDelayed] Print[" <> ToString[i] <> "]", {i, 5}]

{x :> Print[1], x :> Print[2], x :> Print[3], x :> Print[4], x :> Print[5]}

Bob Hanlon
  • 157,611
  • 7
  • 77
  • 198
  • Sorry, but this is about the worst way to solve this IMO. :-( This question is also a duplicate and I am searching for the original(s). – Mr.Wizard Oct 16 '14 at 00:30