Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

How might I remove Removed[..] symbols from the output of an expression?

For example

Clear[b]; b := Sin[a + a]; Remove[a];
b

Sin[2 Removed[a]]

Now as discussed in the story of removed symbols, Removed[a] aren't functions with Heads but symbols with special forms.

This works for catching the symbols.

b /. Cases[b, s_Symbol :> (s :> a), {0, Infinity}, Heads -> True]

But how might I generalize this to all symbols?

Here is my evolving code. ToString[s] == Removed should likely be generalized, but more importantly I can't seem to prevent s:>newHead from going unevaluated.

Replace[b,
 HoldPattern[s_Symbol] :>
  With[{newHead = If[ToString[s] === "Removed[a]"
        a, b
      ]},
    s :> newHead /; True], Infinity
 ]
share|improve this question
add comment

1 Answer

up vote 4 down vote accepted

I think you can use something like this:

b /. s_Symbol /; ! StringQ@MakeBoxes@s :>
       Symbol @ StringTake[ToString@s, {9, -2}]
Sin[2 a]

If a has a value and you don't want a to evaluate in the replacement you'll need something more. This is the best I could think of:

a = "Fail!";  (* this should not appear in the output *)

Module[{hold},
 SetAttributes[hold, HoldAll];
 Hold @@ {b} /. s_Symbol /; ! StringQ@MakeBoxes@s :>
    RuleCondition@ToExpression[StringTake[ToString@s, {9, -2}], InputForm, hold] /.
  {hold[x_] :> x}
]
Hold[Sin[2 a]]

Hold @@ {b} is just an example.

share|improve this answer
add comment

Your Answer

 
discard

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.