3
$\begingroup$

I'm trying to learn stuff from pattern matching but I found sometimes pattern matching does not work as I expected. Could anyone explain why the below outputs are not same? Thank you.

And could anyone also explain why the upvalue setting of b and c cannot use as pattern matching as in my last three codes?

My output on two examples

Clear[a, b, c, g4, g5]
g4[x_^y_, z_] := u[x, y, v[z]] /; {IntegerQ[y], IntegerQ[z]};
g5[x_^y_Integer, z_Integer] := u[x, y, v[z]];
g4[a^3, 2]
g5[a^3, 2]
g4[a^3, c]
g5[a^3, c]
IntegerQ[b] ^= True; IntegerQ[c] ^= True;
g4[a^b, c]
g5[a^b, c]
$\endgroup$

1 Answer 1

4
$\begingroup$

For g4, your condition doesn't evaluate to True or False. Specifically, {IntegerQ[y], IntegerQ[z]} will always evaluate to a pair of booleans, which won't ever actually be equal to True and so that "condition" won't ever be satisfied. You could do something like this instead:

g4[x_^y_, z_] := u[x, y, v[z]] /; And[IntegerQ[y], IntegerQ[z]]

As for the UpSet question, once you fix the condition on g4 and evaluate the UpSet definitions of IntegerQ for b and c, then g4[a^b, c] will evaluate as you expect (u[a, b, v[c]]). However g5[a^b, c] will remain unevaluated, because pattern matching and conditions are different mechanisms that aren't logically interchangeable. But if you had a g6 defined like this:

g6[x_^y_?IntegerQ, z_?IntegerQ] := u[x, y, v[z]]

then g6[a^b, c] would evaluate to u[a, b, v[c]] (again assuming the UpSets for IntegerQ).

A bit more explanation. A pattern like y_Integer matches when the Head of whatever is bound to y is Integer. So, for example,

g5[foo^Integer[bar], Integer[blah]]

will evaluate to

u[foo, Integer[bar], v[Integer[blah]]]

However, even with the corrected condition,

g4[foo^Integer[bar], Integer[blah]]

will evaluate to

g4[foo^Integer[bar], Integer[blah]]

because IntegerQ[Integer[bar]] is False.

$\endgroup$
3
  • $\begingroup$ Hi lericr, I really appreciate your explanation which makes a lot of sense to me. I also tried to define something like g4[x_^y_, z_] := u[x, y, v[z]] /; IntegerQ[y] /; IntegerQ[z]; This one gives same result as your g4 using And function. Are they same thing by any chance? :) $\endgroup$
    – Josh
    Nov 18, 2023 at 17:06
  • $\begingroup$ They aren't the same structurally. Your version is a nested Condition, and mine is a single Condition. But logically they would be equivalent. $\endgroup$
    – lericr
    Nov 18, 2023 at 17:11
  • $\begingroup$ Okay glad to learn all this! The signs in MMA can sometimes be confusing but it is really a good start for me. I'm grateful for your time and help lericr! $\endgroup$
    – Josh
    Nov 18, 2023 at 17:22

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.