5
$\begingroup$

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
 ]
$\endgroup$
6
$\begingroup$

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.

|improve this answer|||||
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.