Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have a rather big expression which contains many sums of form q x + w y. I know that y is much smaller than x and i want to omit it where possible, namely if both q and w are integers. So i apply the replacement rule

q_?IntegerQ x + w_?IntegerQ y -> q x

However this rule obviously doesn't work if either q or w (or both) is equal to unity because FullForm of q x contains Times and one of x doesn't. So to get replacement done i need to use the ugly set of rules

{ q_?IntegerQ x + w_?IntegerQ y -> q x , x + w_?IntegerQ y -> x , ... }

and in place of dots there are two more rules with w and both w and q omitted.

So the question is whether it is possible (in general) to somehow simplify this ugly set to anything more simple.

share|improve this question
BlankNullSequence or {q___?IntegerQ x + w___?IntegerQ y -> q x} – Timothy Wofford Sep 26 '13 at 11:50
Do you want 0s to match? What about q_. x + w_. y /; IntegerQ /@ And[q, w]? – Rojo Sep 26 '13 at 12:03
(Better And @@ IntegerQ /@ {q, w}, otherwise q=w=True would match) – Rojo Sep 26 '13 at 12:17
up vote 6 down vote accepted

You can take advantage of the OneIdentity attribute of Times as it affects pattern matching(1),(2),(3) by making q and w Optional. (As Rojo shows in a comment above.) Condition is then used to check the q and w matches.

{3 x + 7 y, 2 x + E y, x + 5 y} /.
  q_. x + w_. y /; IntegerQ[q] && IntegerQ[w] :> q x
{3 x, 2 x + E y, x}

Note that I used RuleDelayed rather than Rule to localize q.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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