How to Block Symbols without evaluating them?

前端 未结 4 1727
春和景丽
春和景丽 2020-12-28 08:45

Suppose I have a list of names of Symbols:

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

The obvious way to

4条回答
  •  情深已故
    2020-12-28 09:32

    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)

    EDIT

    Yet another alternative (even shorter):

    SetAttributes[blockAlt1, HoldRest];
    blockAlt1[s : {__String}, body_] :=
       Block @@ Append[ToHeldExpression@ToString[s], Unevaluated[body]] 
    

提交回复
热议问题