## How to clear all definitions matching f[1, ...] but not f[2, ...]?

10

2

I would like to clear all definitions of the form f[1,...] in such a way that f[2,...] remain unaffected.

The two methods I know to clear variables don't seem to apply to this situation:

1. Pattern matching with Clear:

Clear[f[1,"*"]] or Clear["f[1,*]"]

2. Using the command =.

f[1,"*"]=.

The second option works for particular values of f[1,...] but doesn't work with pattern matching.

Related, perhaps duplicate: (7972), (19536)

– Mr.Wizard – 2020-06-23T19:18:56.337

15

You can modify DownValues[f] directly. For example

DownValues[f] =
DeleteCases[DownValues[f], HoldPattern[_[f[1, ___]]] :> _]


This works, but I'm a bit confused about the syntax _[...]. Could you explain why the f[1,___] needs brackets around it in this context? – WillG – 2020-05-18T03:59:24.583

@WillG we need to match the HoldPattern as it appears in the DownValues, but without putting it explicitly in the pattern provided to DeleteCase. So we use a Blank. In other words, _[...] matches HoldPattern[...] but doesn't act as a held pattern. It looks confusing because then we have to wrap the pattern in HoldPattern to avoid evaluating the pattern. – Simon Woods – 2020-05-18T19:43:05.893

Ok I think I see. So the HoldPattern that appears explicitly in HoldPattern[_[f[1,___]]] is not what gets matched against the HoldPattern stored in DownValues? – WillG – 2020-05-18T21:42:17.817

@WillG exactly. – Simon Woods – 2020-05-19T18:08:39.290