8
$\begingroup$

I am writing a function that constructs a rule which has Unique[] in the RHS. Here is a simplified segment of code

$userInt = 3;

With[{x = Table[Unique[], {i, 1, 3}]},
  rules = {patt :> x}
]

Here, rules should be look like a list of Unique[], as in

patt :> {Unique[], Unique[], ...}

But the problem is that Unique[] is already evaluated by the With:

rules

(* {patt :> {$48, $48, $48}} *)

How can I generate a list of Unique[] that is not evaluated, but evaluated when it is time to pattern match?

$\endgroup$
  • $\begingroup$ I messed up the code a bit. The upper limit of the Table iterator should be $userInt, not harded-coded 3. $\endgroup$ – QuantumDot Jan 12 '16 at 14:07
3
$\begingroup$
With[{x = Table[HoldForm@Unique[], {i, 1, 3}]}, rules = {patt :> x}]

enter image description here

patt /. (ReleaseHold@rules)

enter image description here

| improve this answer | |
$\endgroup$
9
$\begingroup$

This can be a good case for a Block trick:

Block[{Unique},
  With[{x = Table[Unique[], {i, 1, 3}]}, rules = {patt :> x}]
]

(* {patt :> {Unique[], Unique[], Unique[]}} *)
| improve this answer | |
$\endgroup$
6
$\begingroup$
$userInt = 5;

With[{
  x = Table[Inactive@Unique[], {i, $userInt}]
  }, 
   rules = {_Integer :> x} // Activate
]
{_Integer :> {Unique[], Unique[], Unique[], Unique[], Unique[]}}
{1} /. rules
{{$27, $28, $29, $30, $31}}
| improve this answer | |
$\endgroup$
6
$\begingroup$

So many ways:

Apply[Unique, (patt :> #) & @ Table[{}, {3}], {2}]

(patt :> Evaluate@Table[foo[], {3}]) /. foo -> Unique

Hold[Unique[]][[Range[3]^0]] /. _[x__] :> (patt :> {x})

(patt :> {##}) & @@ Table[Unevaluated @ Unevaluated @ Unique[], {3}]

(Function @@ {patt :> Evaluate@Table[#[], {3}]}) @ Unique

All produce:

patt :> {Unique[], Unique[], Unique[]}

But I must say I don't see why you wouldn't just use:

rule = patt :> Table[Unique[], {3}];

patt /. rule
patt /. rule
{$3, $4, $5}

{$6, $7, $8}
| improve this answer | |
$\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.