5
$\begingroup$

I'd like to replace fractions with Missing[] as the denominator with Missing[]. This pattern in ReplaceAll does not do the job:

ReplaceAll[{1/Missing[], 2}, (_/Missing[] :> Missing[])]

But the exact match works fine:

ReplaceAll[{1/Missing[], 2}, (1/Missing[] :> Missing[])]

Why is this?

$\endgroup$
3
  • $\begingroup$ In the interest of helping you help yourself: look at FullForm[{1/Missing[], _/Missing[]}]. It should be quickly apparent why you're not getting what you want. $\endgroup$ Oct 22, 2015 at 23:34
  • $\begingroup$ ...and since you're matching denominators only: you know there's a Denominator[] function, yes? $\endgroup$ Oct 22, 2015 at 23:36
  • $\begingroup$ As an extension to the comments above , {a/Missing[ ],2}/. _/Missing[]:>Missing[ ] will work for any a .... except 1 :) $\endgroup$ Oct 22, 2015 at 23:40

2 Answers 2

5
$\begingroup$

By using the optional value in the pattern, there is no special case:

ReplaceAll[{1/Missing[], 2/Missing[], 3}, _./Missing[] :> Missing[]]

(* {Missing[], Missing[], 3} *)
$\endgroup$
3
$\begingroup$

1/Missing[] is a special case, equivalent to Missing[]^-1. This is why the original pattern matches 2/Missing[]. I guess the best way is to handle it separately:

ReplaceAll[{1/Missing[], 2/Missing[], 3}, {_/Missing[] :> Missing[], 1/Missing[] :> Missing[]}]

(Thanks to J.M. and belisarius for the hints.)

$\endgroup$
1
  • $\begingroup$ Actually, I'd have done {1/Missing[], 2/Missing[], 3} /. x_ /; Denominator[x] === Missing[] :> Missing[]. ;) $\endgroup$ Oct 23, 2015 at 0:07

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.