问题描述
限时送ChatGPT账号..假设我有一个 Symbol
的名称列表:
Suppose I have a list of names of Symbol
s:
f1 := Print["f1 is evaluated!"];
list = {"f1", "f2"};
Block
这些Symbol
的显而易见的方法是对它们进行评估:
The obvious way to Block
these Symbol
s leads to evaluation of them:
In[19]:= With[{list=Symbol/@list},Block[list,f1//ToString]]
During evaluation of In[19]:= f1 is evaluated!
During evaluation of In[19]:= f1 is evaluated!
Out[19]= Null
但无需评估,我们就可以阻止
它们而不会出现任何问题:
But without evaluation we could Block
them without any problem:
In[20]:= Block[{f1, f2}, f1 // ToString]
Out[20]= "f1"
是否可以在不评估 Symbol
的情况下将此列表注入 Block
范围?
Is it possible to inject this list into the Block
scope without evaluating the Symbol
s?
推荐答案
这是实现此目的的另一种技术:
Here is yet another technique to do this:
SetAttributes[blockAlt,HoldRest];
blockAlt[s : {__String}, body_] :=
Replace[Join @@ ToHeldExpression[s], Hold[x__] :> Block[{x}, body]]
由于规则的破坏性(它们不尊重其他作用域构造,包括它们自己),我们在此保留纯函数
We save here on pure functions, due to the disruptive nature of rules (they don't respect other scoping constructs, including themselves)
编辑
另一种选择(甚至更短):
Yet another alternative (even shorter):
SetAttributes[blockAlt1, HoldRest];
blockAlt1[s : {__String}, body_] :=
Block @@ Append[ToHeldExpression@ToString[s], Unevaluated[body]]
这篇关于如何在不评估它们的情况下阻止符号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论