I wish to take some expression containing instances of Pattern[]
, and rename the variables of those patterns based on evaluation featuring the variable.
Let's say my renaming function is
f[s_Symbol] := Symbol[ SymbolName[s] <> "2" ]
which just appends 2 to symbol names:
f[a]
>>> a2
If I try to replace Pattern
variables with this function (or any expression), that expression remains unevaluated!
a_ /. a :> f[a]
>>> Pattern[ f[a], _ ]
I assume Pattern
holds its first argument.
Naturally my example is strange since simplified; I really intend to replace any symbol (which may or may not be featured in a Pattern
) which satisifes certain properties.
a_ /. s_Symbol /; someTest[s] :> f[s]
>>> Pattern[ f[a], _ ]
How can I force Pattern
to evaluate its first argument after my substitution? This may appear like the general question of "how to substitute variables of functions that hold their arguments", but alas, the documented technique for that does not seem to apply here:
a_ /. a :> With[{x=f[a]}, x]
>>> Pattern[With[{x = f[a]}, x], _]
I cannot just insert an Evaluate
into the RHS of my DelayedRule
(though that would solve my first hard-coded example), since this just violates the rule delay, and invokes f[s]
.
EDIT
Here's an example to test candidate solutions with:
f[s_] := Symbol[ SymbolName[s] <> "2"];
test[s_] := (s =!= Pattern && s =!= Blank)
a_ /. s_Symbol /; test[s] :> f[s]
>>> Pattern[f[a], _]
(* desired output: Pattern[a2, _] *)
Pattern
holds its first argument." -MemberQ[Attributes[Pattern], HoldFirst]
returnsTrue
, so... $\endgroup$f
will work if you callSymbol
with the correct syntax:Symbol[ SymbolName[s] <> "2" ]
$\endgroup$f[a]
remains unevaluated in my example, despite the definition off
... $\endgroup$f[a]
(instead off[s]
), that is obviously not what I want $\endgroup$