如何在不评估它们的情况下阻止符号? [英] How to Block Symbols without evaluating them?

查看:32
本文介绍了如何在不评估它们的情况下阻止符号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个 Symbol 的名称列表:

Suppose I have a list of names of Symbols:

f1 := Print["f1 is evaluated!"];
list = {"f1", "f2"};

Block这些Symbol的显而易见的方法是对它们进行评估:

The obvious way to Block these Symbols 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 Symbols?

推荐答案

这是实现此目的的另一种技术:

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屋!

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