5
$\begingroup$

Pattern recognition doesn't work as I would expect when trying to match products, for example

Cases[a[1] b[1] a[2] b[2], x___ a[k_] b[k_] -> k, All]

{1}

Cases[a[1] b[1] a[2] b[2], a[k_] b[k_] -> k, All]

{}

But none of these two return {1,2} as I would expect. How to cure this problem ?

Thanks.

$\endgroup$

2 Answers 2

6
$\begingroup$

It works as expected. It matches the whole expression at once:

Cases[a[1] b[1] a[2] b[2], x___ a[k_] b[k_], All]
(* {a[1] a[2] b[1] b[2]} *)

If you want to get all possible matches, please look at ReplaceList, which:

attempts to transform the entire expression expr by applying a rule or list of rules in all possible ways, and returns a list of the results obtained.

ReplaceList[a[1] b[1] a[2] b[2], x___ a[k_] b[k_] :> k]
(* {1, 2} *)
$\endgroup$
2
  • $\begingroup$ Thanks a lot for your comment, it was really helpful! Also why does ReplaceList[a[1]^2 , x___ a[k_]^2 :> k] return {} instead of {1} ? $\endgroup$ Commented Mar 12 at 18:00
  • $\begingroup$ @AdrienMartina why are you using triple blank? Just use the regular blank, and make it optional: ReplaceList[a[1]^2 , x_. a[k_]^2 :> k] . But note that you can use plain Cases in this case. $\endgroup$
    – Domen
    Commented Mar 12 at 19:02
5
$\begingroup$
p = a[1] b[1] a[2] b[2];

SequenceCases[List @@ p, {a[k_], b[k_] ...} :> k]

{1, 2}

$\endgroup$

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.