Message Boards Message Boards

5
|
4187 Views
|
0 Replies
|
5 Total Likes
View groups...
Share
Share this post:

Clearing OwnValues, DownValues, UpValues and SubValues separately

In a recent code I'm doing I needed to clear the OwnValue of a variable to assign a UpValue to it, thus I needed to clear the OwnValue, and only it, otherwise I would get nonsense.

As far as I know, Mathematica doesn't seem to have a function with this capability. With bits and pieces from all over I could work-out these functions (hacks):

SetAttributes[{ClearOwnValues, ClearDownValues, ClearUpValues, ClearSubValues}, HoldFirst]

ClearOwnValues[var_Symbol] := (OwnValues@var = {};)
ClearUpValues[var_Symbol] := (UpValues@var = {};)

ClearDownValues[f_Symbol[args___]] := (DownValues@f = DeleteCases[DownValues@f, _?(!FreeQ[First@#, HoldPattern@f[args]] &)];)
ClearUpValues[f_Symbol[args___]] := (UpValues@f = DeleteCases[UpValues@f, _?(!FreeQ[First@#, HoldPattern@f[args]] &)];)
ClearSubValues[f_Symbol[args___][args2___]] := (SubValues@f = DeleteCases[SubValues@f, _?(!FreeQ[First@#, HoldPattern@f[args][args2]] &)];)

Where the last three definitions are basically the same thing (I could probably make it less ugly, but...). A working example would be:

Re@f[x_] ^:= x^2
f[w_][n_] := 1
f[x_] + g[x_] ^:= "Hey"
f[z_] := Cos[z]
f = 3;

ShowValues := # -> #[f] & /@ {OwnValues, DownValues, UpValues, SubValues} // TableForm

Where we have assigned all kind of "Values" to f and created a function to show it. Show

Where in each line of code we deleted a *Value. A example of real usage would be:

SetAttributes[Test, HoldFirst]
DefineReal[var_Symbol] /; ClearOwnValues@var := Im@var = 0
a = 1;
DefineReal[a]
a === 1

Which return False as expected. Other usage would be simply ClearDownValues[Subscript[f, _]], since Mathematica can't Clear expressions like this, it prove to be extremely usefull.

POSTED BY: Thales Fernandes
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract