6
$\begingroup$

I am using v12.2.0 on Win7-x64. I want to use Cases to select the Times and Plus cases from the following list.

Clear["Global`*"]
expr = {2 a, 2 b, a + b, 2 c, a + c, b + c, 2 d, a + d, b + d, c + d};

expr // FullForm

List[Times[2,a],Times[2,b],Plus[a,b],Times[2,c],Plus[a,c],Plus[b,c],Times[2,d],Plus[a,d],Plus[b,d],Plus[c,d]]

Cases 1/2/3 work fine.

Case 1

{Cases[expr, Plus[a_, b_], {1}], Cases[expr, Times[a_, b_], {1}]}

{{a + b, a + c, b + c, a + d, b + d, c + d}, {2 a, 2 b, 2 c, 2 d}}

Case 2

{Cases[expr, a_ + b_, {1}], Cases[expr, a_  b_, {1}]}

{{a + b, a + c, b + c, a + d, b + d, c + d}, {2 a, 2 b, 2 c, 2 d}}

Case 3

{Cases[expr, _Plus, {1}], Cases[expr, _Times, {1}]}

{{a + b, a + c, b + c, a + d, b + d, c + d}, {2 a, 2 b, 2 c, 2 d}}

Case 4

Using a Blank does not work.

{Cases[expr, Plus[_], {1}], Cases[expr, Times[_], {1}]}

{{2 a, 2 b, a + b, 2 c, a + c, b + c, 2 d, a + d, b + d, c + d}, {2 a, 2 b, a + b, 2 c, a + c, b + c, 2 d, a + d, b + d, c + d}}

Case 5

Using a BlankSequence does not work either.

{Cases[expr, Plus[__], {1}], Cases[expr, Times[__], {1}]}

{{2 a, 2 b, a + b, 2 c, a + c, b + c, 2 d, a + d, b + d, c + d}, {2 a, 2 b, a + b, 2 c, a + c, b + c, 2 d, a + d, b + d, c + d}}

Case 6

This is the most weird one. Plus[_,_] returns the multiplied terms and the Times[_,_] returns nothing

{Cases[expr, Plus[_, _], {1}], Cases[expr, Times[_, _], {1}]}

{{2 a, 2 b, 2 c, 2 d}, {}}

Case 7

Reintroducing one named pattern makes it work again. Making it two named patterns would get us back to Case 1.

{Cases[expr, Plus[x_, _], {1}], Cases[expr, Times[x_, _], {1}]}

{{a + b, a + c, b + c, a + d, b + d, c + d}, {2 a, 2 b, 2 c, 2 d}}

Case 8

This one works but i don't understand it.

{Cases[expr, Plus[_, __], {1}], Cases[expr, Times[_, __], {1}]}

{{a + b, a + c, b + c, a + d, b + d, c + d}, {2 a, 2 b, 2 c, 2 d}}

Can someone please help me understand this better? Thanks.

$\endgroup$
3
  • 4
    $\begingroup$ It's a matter of evaluation order. The analysis in e.g. mathematica.stackexchange.com/a/280488/1871 is fully applicable to your problem. $\endgroup$
    – xzczd
    Commented May 8, 2023 at 10:20
  • 4
    $\begingroup$ Some other strongly related posts: mathematica.stackexchange.com/a/280250/1871 mathematica.stackexchange.com/a/124224/1871 $\endgroup$
    – xzczd
    Commented May 8, 2023 at 10:37
  • 1
    $\begingroup$ Many thanks @xzczd. Evaluating these: {Plus[_], Plus[__], Plus[_, _], Plus[_, __], Plus[a_, _]} has helped clear the confusion. Plus[_, _] gets evaluated to 2 _ (Case 6) and coincidentally there were some 2 _ terms. Cases 4/5/6 were resolve with HoldPattern. $\endgroup$
    – Syed
    Commented May 8, 2023 at 13:02

0

Your Answer

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