You're mixing DownValues
rules made with SetDelayed
(:=
) and replacement rules. Without seeing your application I cannot tell why. If you provide more information about your application a different approach may be recommended.
I see two problems with your code right off the bat. First:
MyHead1[x_] := Replace[MyHead1[x], MyRule1];
Here you made a definition that evaluates to itself in an unheld form. This causes infinite recursion.
Second, by defining:
MyRule1 = MyHead1[x_MyHead2] | MyHead1[x_MyHead3] :> x; (* note use of :> to localize x *)
MyHead1[x_] := "anything"
MyRule1
evaluates to "anything" | "anything" :> x
as soon as it is accessed.
The second problem might be corrected with HoldPattern
:
MyRule1 = HoldPattern[MyHead1[x_MyHead2] | MyHead1[x_MyHead3]] :> x;
The first is more complicated. I still suppose that you may want instead to write this to avoid the recursion in the first place, but alternatively you could work within Hold
:
ClearAll[MyHead1]
MyHead1[x_] := Replace[Hold[MyHead1[x]], MyRule1, {1}]; (* note Levelspec *)
Or you could use the Villegas-Gayley method:
ClearAll[MyHead1]
MyHead1[x_] /; ! TrueQ[insideMyHead1] :=
Block[{insideMyHead1 = True},
Replace[MyHead1[x], MyRule1]
]
I suspect instead of all this you may be looking for the functionality of UpSet
, UpSetDelayed
, TagSet
, etc. which make UpValues
rules. Again, with a more complete problem specification I may be able to recommend something better.
Lastly, the title of your question makes me think that perhaps you would find value in this special use of Condition
:
lhs := Module[{vars}, rhs /; test] allows local variables to be shared
between test and rhs. You can use the same construction with Block and
With.