0
$\begingroup$

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, _] *)
$\endgroup$
10
  • 1
    $\begingroup$ "I assume Pattern holds its first argument." - MemberQ[Attributes[Pattern], HoldFirst] returns True, so... $\endgroup$ Feb 2, 2021 at 12:45
  • 1
    $\begingroup$ You definition of f will work if you call Symbol with the correct syntax: Symbol[ SymbolName[s] <> "2" ] $\endgroup$ Feb 2, 2021 at 13:30
  • $\begingroup$ @J.M. so my assumption was correct? $\endgroup$
    – Anti Earth
    Feb 2, 2021 at 14:21
  • $\begingroup$ @DanielHuber no, it won't. That's a typo in my MWE, that isn't relevant to the evaluation; clearly you can see f[a] remains unevaluated in my example, despite the definition of f... $\endgroup$
    – Anti Earth
    Feb 2, 2021 at 14:25
  • 1
    $\begingroup$ @RomaLee You're hard-coding f[a] (instead of f[s]), that is obviously not what I want $\endgroup$
    – Anti Earth
    Feb 2, 2021 at 15:04

1 Answer 1

2
$\begingroup$

Evaluation of the replacing expression can be forced (at replacement time) using the undocumented RuleCondition, as described here.

f[s_] := Symbol[ SymbolName[s] <> "2"];

test[s_] := (s =!= Pattern && s =!= Blank)

a_ /. s_Symbol /; test[s] :> RuleCondition[f[s]]

>>> a2_
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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