在Mathematica中打印符号名称和值 [英] Printing symbol name and value in Mathematica
问题描述
我想创建一个函数My`Print[args__]
,该函数打印我传递的符号的名称以及它们的值.问题在于,在将符号传递给My`Print
之前,需要对它们进行评估.因此My`Print
永远都看不到符号名称.
I'd like to create a function My`Print[args__]
that prints the names of the symbols that I pass it, along with their values. The problem is that before the symbols are passed to My`Print
, they're evaluated. So My`Print
never gets to see the symbol names.
一种解决方案是用Unevaluated[]
包围我传递给My`Print
的每个参数,但这似乎很混乱.有没有一种定义MACRO的方式,当我键入My`Print[args__]
时,Mathematica内核会看到My`Print[Unevaluated /@ args__]
?
One solution is to surround every argument that I pass to My`Print
with Unevaluated[]
, but this seems messy. Is there a way of defining a MACRO such that when I type My`Print[args__]
, the Mathematica Kernel sees My`Print[Unevaluated /@ args__]
?
推荐答案
您需要设置属性这是可能的实现方式:
Clear[my`print]
SetAttributes[my`print, HoldAll]
my`print[args__] :=
Scan[
Function[x, Print[Unevaluated[x], " = ", x], {HoldAll}],
Hold[args]
]
我使用小写名称来避免与包中的内置函数或函数发生冲突.
I used lowercase names to avoid conflicts with built-ins or functions from packages.
仅需明确说明:我在这里有两个功能.一个将打印一个单个符号的值,并在其中实现为Function
.如果足够,您可以单独使用它.另一个是实际的my`print
函数.请注意,两者都必须具有HoldAll
属性.
Just to make it explicit: I have two functions here. One will print the value of a single symbol, and is implemented as a Function
inside. You can just use this on its own if it's sufficient. The other is the actual my`print
function. Note that both need to have the HoldAll
attribute.
这篇关于在Mathematica中打印符号名称和值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!