如何在不评估它们的情况下阻止符号?

编程入门 行业动态 更新时间:2024-10-24 02:24:48
本文介绍了如何在不评估它们的情况下阻止符号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

假设我有一个 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屋!

更多推荐

[db:关键词]

本文发布于:2023-04-25 07:26:02,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1080287.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:符号   情况下   如何在

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!