2
$\begingroup$

This question already has an answer here:

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?

$\endgroup$

marked as duplicate by Mr.Wizard Oct 16 '14 at 0:35

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

4
$\begingroup$

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]
$\endgroup$
0
$\begingroup$
ToExpression@
 Table["x \[RuleDelayed] Print[" <> ToString[i] <> "]", {i, 5}]

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

$\endgroup$
  • $\begingroup$ 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). $\endgroup$ – Mr.Wizard Oct 16 '14 at 0:30

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