I'm now practicing pattern matching by implementing a self-defined differentiation operator.

diff[fx_ + gx_, x_] := diff[fx, x] + diff[gx, x]
diff[c_*fx_, x_] /; FreeQ[c, x] := c*diff[fx, x]
diff[x_^n_., x_] /; FreeQ[n, x] := n*(x^(n - 1))

I test it with

diff[9^a, x]
diff[3, x]

But these two expressions do not further evaluate to the "correct" result. Where is the mistake?


1 Answer 1


Of the two examples you show, neither of them matches any of the diff patterns you declared:

  • In the case of diff[9^a, x], note that your last pattern (diff[x_^n_., x_] /; FreeQ[n, x]) requires that the base of the first argument and the second argument both be x, so diff[x^a, x] or diff[9^a, 9] would match, but not diff[9^a,x].
  • In the case of diff[3,x], you have no form of diff that matches on a single value in the first argument; you'd need something like diff[q_,x_] possibly with a requirement like diff[q_?NumericQ, x_]. This case does not match your third diff declaration either because 3 is not x.
  • $\begingroup$ Oh, I see! I was too focusing on ^n_., thinking it is the place where the problems arose. Thanks for the help. $\endgroup$
    – Eric
    Commented Mar 1, 2018 at 14:01

Your Answer

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

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