Mathematica:如何清除符号的缓存,即取消设置无模式的 DownValues [英] Mathematica: How to clear the cache for a symbol, i.e. Unset pattern-free DownValues

查看:41
本文介绍了Mathematica:如何清除符号的缓存,即取消设置无模式的 DownValues的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一个糟糕的缓存者:有时,当没有人观看时,我会缓存结果而不包含完整的上下文,如下所示:

I'm a bad cacher: Sometimes, when no one is watching, I'll cache results without including the full context like so:

f[x_]:=f[x]=x+a;
a=2; f[1];
DownValues[f]

Out[2]= {HoldPattern[f[1]]:>3,HoldPattern[f[x_]]:>(f[x]=x+a)}

这会导致非常微妙的错误,更重要的是,当我更改上下文时需要清除缓存.清除缓存的一种方法是完全Clear 符号并重复定义,但这并不是真正的解决方案.

This leads to horribly subtle bugs, and, more importantly, to the need for clearing the cache when I change the context. One way of clearing the cache is to completely Clear the symbol and repeat the definitions, but this is not really a solution.

我真正想要的是一种清除与符号关联的所有无模式 DownValues 的方法.
为清楚起见,我将包括我目前的解决方案作为答案,但如果在两个方面失败

What I would really like is a method for clearing all pattern-free DownValues associated with a symbol.
For clarity, I'll include my present solution as an answer, but if fails on two counts

  • 它只清除带有全数字参数的 DownValues
  • 出于美观原因,我想避免使用 Block 来获取 DownValues.
  • It only clears DownValues with all-numeric arguments
  • For aesthetical reasons, I'd like to avoid using Block to grab the DownValues.

关于如何改进 ClearCache 的任何想法?

Any ideas on how to improve ClearCache?

推荐答案

我以前做过类似的功能(但我不记得在哪里了).

I've made similar functions in the past (but I can't remember where).

以下代码是否满足您的所有需求?

Does the following code do all that you need?

ClearCache[f_] := DownValues[f] = DeleteCases[DownValues[f], 
                                              _?(FreeQ[First[#], Pattern] &)]

这可能应该扩展到UpValuesSubValues.而fHead限定为Symbol.

This maybe should be extended to UpValues and SubValues. And the Head of f restricted to Symbol.

这篇关于Mathematica:如何清除符号的缓存,即取消设置无模式的 DownValues的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆