1

I often find myself doing something like this (probably poor example, sorry)

f[x_] := 0
f[x_Plus] := 1

In the back of my mind generally f[x] is zero but in an exceptional case when the argument is a sum f[x] gives 1. This is exactly what Mathematica thinks as well

{f[a], f[a + b]}

returns {0,1}. If it were not for the "exceptional" rule for f[x_Plus] both results would be zero.

What is the general rule how similar conflicts are resolved?

Weather Report
  • 535
  • 2
  • 15
  • 2
    Mathematica applies orders definitions by their "specificity". Since f[x_Plus] is more specific than f[x_], it will be tried first. See How is pattern specificity decided? – C. E. Sep 04 '20 at 12:15
  • @C.E. This is helpful, thank you. However the discussion down your link is a bit theoretical. Is there any practical advice on a good programming practice here? I expect it should be easy to get in trouble on this path. – Weather Report Sep 04 '20 at 12:23
  • 5
    Transformation Rules and Definitions The Ordering of Definitions, "When you make a sequence of definitions ..., some may be more general than others. The Wolfram System follows the principle of trying to put more general definitions after more specific ones. ... special cases of rules are typically tried before more general cases. ... Often, however, there is no definite ordering in generality of the rules you give. In such cases, the Wolfram System simply tries the rules in the order you give them. " – Bob Hanlon Sep 04 '20 at 12:37
  • 2
    To answer the question about good programming practice, I think that ordering patterns by specificity is not as problematic as you suspect. I can't remember the last time that I ran into such a problem. However, I have seen some people use trickery such as appending /; True to the definitions to prevent Mathematica from computing their specificity, so that the patterns will be ordered in the same order as the definitions in the source code. I guess good practice is avoid such trickery, and make definitions such that it is obvious to the reader in which order they are meant to be tried. – C. E. Sep 04 '20 at 20:11

0 Answers0