Ale*_*kov 5 wolfram-mathematica
如何获得与其他符号由相关的符号的所有定义TagSet,TagSetDelayed,UpSet或UpSetDelayed?
例如,如果已定义
area[square] ^= s^2
area[cube] ^= 6*s^2
Run Code Online (Sandbox Code Playgroud)
如何获取这些定义,不知道名称square,cube但只知道名称area?
我发现,UpValues不返回定义MakeBoxes和N因为它们被存储在FormatValues与NValues相应:
In[1]:= rotate /: MakeBoxes[expr_rotate, "StandardForm"] := x
UpValues[rotate]
FormatValues[rotate]
Out[2]= {}
Out[3]= {HoldPattern[MakeBoxes[expr_rotate, "StandardForm"]] :> x}
In[4]:= pi /: N[pi] = 3.14
UpValues[pi]
NValues[pi]
Out[4]= 3.14
Out[5]= {}
Out[6]= {HoldPattern[N[pi, {MachinePrecision, MachinePrecision}]] :>
3.14}
Run Code Online (Sandbox Code Playgroud)
通过这种方式,而不是UpValues我们应该使用的组合UpValues,FormatValues和NValues.
当试图输出列表FormatValues一个能面对的问题MakeBoxes,因为FormatValues给出的定义MakeBoxes那些通过进一步处理MakeBoxes创建针对前端输出.通过FormatType临时切换OutputForm或将这些定义转换为字符串可以解决此问题.
In[1]:= SetOptions[$Output,FormatType->OutputForm];
FormatValues[DialogNotebook]
Out[2]= {HoldPattern[MakeBoxes[BoxForm`apat$:HoldPattern[DialogNotebook[___]], BoxForm`fpat$_]] :>
BoxForm`BoxFormAutoLoad[MakeBoxes, BoxForm`apat$, BoxForm`fpat$, Typeset`CellNotebook`,
{{CellGroup, _}, {DocumentNotebook, _}, {PaletteNotebook, _}, {DialogNotebook, _}, {ExpressionCell, _}, {Text, _},
{TextCell, _}, {Cell, HoldPattern[MakeExpression[_Cell, _]]}, {Notebook, HoldPattern[MakeExpression[_Notebook, _]]}}]}
In[1]:= ToString@FormatValues[DialogNotebook]
Out[1]= {HoldPattern[MakeBoxes[BoxForm`apat$:HoldPattern[DialogNotebook[___]], BoxForm`fpat$_]] :> BoxForm`BoxFormAutoLoad[MakeBoxes, BoxForm`apat$, BoxForm`fpat$, Typeset`CellNotebook`, {{CellGroup, _}, {DocumentNotebook, _}, {PaletteNotebook, _}, {DialogNotebook, _}, {ExpressionCell, _}, {Text, _}, {TextCell, _}, {Cell, HoldPattern[MakeExpression[_Cell, _]]}, {Notebook, HoldPattern[MakeExpression[_Notebook, _]]}}]}
Run Code Online (Sandbox Code Playgroud)
为了解决阿列克谢对霍华德回答的担忧,我想出了这个:
Cases[
UpValues @@@ MakeExpression /@ Names["Global`*"],
HoldPattern[_@_area :> _],
{2}
]
Run Code Online (Sandbox Code Playgroud)
为了响应您更新的要求,这里是高级版本:
SetAttributes[otherValues, HoldFirst]
otherValues[sym_] :=
With[{names = MakeExpression /@ Names["Global`*"]},
Join[
Cases[UpValues @@@ names, HoldPattern[_@_sym :> _], {2}],
Cases[NValues @@@ names, HoldPattern[_@N[sym, ___] :> _], {2}],
Select[Join @@ FormatValues @@@ names, ! FreeQ[#, HoldPattern@sym] &]
]
]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
485 次 |
| 最近记录: |