2

I have a bunch of symbols which are collected as a list inside a variable within a bit of code e.g.

a=1;b=2;
par={a,b};

I want to clear the values of both a and b using only a reference to par. Here is my attempt and the error produced:

Clear[Sequence@@par]
... Clear::ssym: Sequence@@par is not a symbol or a string.

I can understand why this gives an error but can't figure out a way out of it.

Thanks for your help

jrekier
  • 525
  • 2
  • 9

2 Answers2

1

This will not work. Because you used Set, not SetDelayed. After executing this code:

a = 1; 
b = 2; 

par = {a, b}
OwnValues[par]

(*
    {1, 2}
    {HoldPattern[par] :> {1, 2}}
*)

par isn't a list with a and b. par is a list that contains {1, 2}.

For your task you can use this code:

a = 1; 
b = 2; 

par := {a, b}
par
OwnValues[par]

(* 
    {1, 2}
    {HoldPattern[par] :> {a, b}} 
*)

Now you must take list of values from OwnValues rule:

Hold[par] /. OwnValues[par]

(* Hold[{a, b}] *)

And if you want clear a and b:

Hold[par] /. OwnValues[par] /. Hold[{args__}] :> Clear[args]

par
{a, b}

(* 
    {a, b} 
    {a, b}
*)

Definition for par preserved and for a and b cleared

Kirill Belov
  • 618
  • 6
  • 17
0

As others correctly pointed out, there is no way to establish variable names after the fact in this case. But if you have traced your code, which is a big if, of course, but imagine you did:

trace = Trace[
   a = 1; b = 2;
   par = {a, b}
];

Then you can fish out the variable names that were used during assignment and clear them:

Cases[
    trace,
    HoldPattern[par = vars : {___Symbol}] :> ClearAll @@ Unevaluated @ vars,
    All
];
swish
  • 7,881
  • 26
  • 48