3
$\begingroup$

Why BlankNullSequence rest___ is not matched with nothing (empty expression) ?

a^2 /. Times[rest___, x_^2] -> 2
(* a^2 *)

a^2 /. Plus[rest___, x_^2] :> 2
(* a^2 *)

Should not the answer be 2 in both cases ? How should be the pattern for that ?

$\endgroup$
2
  • $\begingroup$ The rule will not match because $a^2$ head is Power, and therefore will be ignored. $\endgroup$ Commented Mar 13, 2017 at 12:47
  • $\begingroup$ @AnjanKumar, So what is wrong with the head Power ? Both a^2 and x_^2 have the same head Power. $\endgroup$
    – Mher
    Commented Mar 13, 2017 at 12:49

1 Answer 1

3
$\begingroup$

You are asking to match a pattern that has a head of Times and your expression has a head of Power.

Use something like:

a^2 /. Times[n_., x_^2] -> 2

to do what you require. See the documentation for Default (n_.) and OneIdentity. OneIdentity is the attribute of Plus and Times which tells Mathematica that Times[x] is the same as x.

$\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.