Latest update

# Apply Clear puzzle

2018-01-24 07:02:52

This is OK

foo=1; bar=2;

Clear[foo,bar]

But this is not

foo=1; bar=2;

Clear@@{foo,bar}

Clear::ssym: 1 is not a symbol.

Clear::ssym: 2 is not a symbol.

So how do you Clear a list of symbols?

I understand that clearing a list of strings that name those symbols, as in This ansswer is possible. But that's not what I'm asking.

Note that this is happening in your code because by the time Clear gets to the variables, List ({}) has evaluated them and Clear tries to operate on 1 and 2, which is of course nonsense.

Consider the clearList function here:

In[1]:= x = y = z = 2;

In[2]:= clearList[lis_List] :=

ReleaseHold[Map[Clear, HoldComplete[lis], {2}]]

SetAttributes[clearList, HoldFirst]

In[4]:= x = y = z = 2;

In[5]:= {x, y, z}

Out[5]= {2, 2, 2}

In[6]:= clearList[{x, y, z}]

Out[6]= {Null, Null, Null}

In[7]:= {x, y, z}

Out[7]= {x, y, z}

This is what I use, there may be better ways to do it.

I would store a list of the variable symbol names instea

• Note that this is happening in your code because by the time Clear gets to the variables, List ({}) has evaluated them and Clear tries to operate on 1 and 2, which is of course nonsense.

Consider the clearList function here:

In[1]:= x = y = z = 2;

In[2]:= clearList[lis_List] :=

ReleaseHold[Map[Clear, HoldComplete[lis], {2}]]

SetAttributes[clearList, HoldFirst]

In[4]:= x = y = z = 2;

In[5]:= {x, y, z}

Out[5]= {2, 2, 2}

In[6]:= clearList[{x, y, z}]

Out[6]= {Null, Null, Null}

In[7]:= {x, y, z}

Out[7]= {x, y, z}

This is what I use, there may be better ways to do it.

2018-01-24 07:50:24
• I would store a list of the variable symbol names instead of the symbols:

vlist = {"foo", "bar"};

foo = 1; bar = 2;

Clear @@ vlist

foo

bar

foo

bar

If you are copy/pasting the list of symbol names, then I think the following function would be simplest:

SetAttributes[clear, HoldAll]

clear[{a__}] := Clear[a]

x=2; y=2; z=2;

clear[{x, y, z}]

{x, y, z}

{x, y, z}

2018-01-24 08:02:39