# Apply rule only if applicable? Check rule applicability? Custom unapplicable rule?

How to avoid recursion in the following example?

Clear[MyRule];

How to make first rule in example below treated by Replace as not applicable?

In[17]:= ComplexRule1 = a -> Block[{},
12
];

In[18]:= ComplexRule2 = a -> Block[{},
13
];

In[19]:= Replace[a, {ComplexRule1, ComplexRule2}]

Out[19]= 12
-
You're asking a rapid-fire series of questions about pattern matching. I am assuming this is all part of a particular application. What is it? – Mr.Wizard Jan 19 '13 at 10:56
I want to implement custom algebra with custom heads, transformations and simplifications. I am surprised Mathematica is not well suitable for this. – Suzan Cioc Jan 19 '13 at 11:03
The main problem is "preprocessing". If user enters some expression with some heads, it should be automatically transformed into expressions with same heads, but simplified and normalized. This causes recursions for me. Conditions work bad here because they can require complex computations. – Suzan Cioc Jan 19 '13 at 11:15
@kguler it's ok – Suzan Cioc Jan 19 '13 at 11:20
"I am surprised Mathematica is not well suitable for this." — usually when someone says this, it's more often the case that they haven't thought through their problem well enough or are unfamiliar with Mathematica. I don't know which one it is :) – R. M. Jan 19 '13 at 17:17

I see two problems with your code right off the bat. First:

Here you made a definition that evaluates to itself in an unheld form. This causes infinite recursion.

Second, by defining:

MyRule1 evaluates to "anything" | "anything" :> x as soon as it is accessed.

The second problem might be corrected with HoldPattern:

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:

Or you could use the Villegas-Gayley method: