本文介绍了如何拦截为 In 变量分配新值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望拦截为 In 变量分配新值.

I wish to intercept assigning new values for the In variable.

我试图通过为 In 定义 UpValues 来做到这一点,但在这种情况下它没有帮助:

I have tried to do this by defining UpValues for In but it does not help in this case:

Unprotect[In];
In /: Set[In[line_], expr_] /; ! TrueQ[$InsideSet] :=
 Block[{$InsideSet = True},
  Print[HoldForm@HoldForm[expr]; Set[In[line], expr]]]
In /: SetDelayed[In[line_], expr_] /; ! TrueQ[$InsideSet] :=
 Block[{$InsideSet = True},
  Print[HoldForm@HoldForm[expr]; SetDelayed[In[line], expr]]]

可以拦截吗?

附言这个问题作为上一个问题的一部分出现在Mathematica 创建新的 Symbols.

P.S. This question has arisen as a part of previous question on the stage when Mathematica creates new Symbols.

我希望显式拦截 In 变量的赋值 new DownValue.$Pre 执行 after 这个赋值和 after 在当前 $ContextSymbol/代码>:

I would wish to intercept explicitly the assignment new DownValue for the In variable. $Pre executes after this assignment and after creating all new Symbols in the current $Context:

In[1]:= $Pre := (Print[Names["`*"]];
   Print[DownValues[In][[All, 1]]]; ##) &

In[2]:= a

During evaluation of In[2]:= {a}

During evaluation of In[2]:= {HoldPattern[In[1]],HoldPattern[In[2]]}

Out[2]= a

推荐答案

你看过 $Pre$PreRead?

$Pre 是一个全局变量,其值(如果设置)将应用于每个输入表达式.

$Pre is a global variable whose value, if set, is applied to every input expression.

$PreRead 是一个全局变量,如果设置了它的值,它会在输入到 Mathematica 之前应用于每个输入表达式的文本或框形式.

$PreRead is a global variable whose value, if set, is applied to the text or box form of every input expression before it is fed to Mathematica.

更新(现在有更好的示例)

In[1]:= $Pre =
  Function[{x}, Print["In[",$Line,"] is: ", Unevaluated[x]]; x, HoldFirst];

In[2]:= 2 + 2

During evaluation of In[2]:= In[2] is: 2+2

Out[2]= 4

In[3]:= InString[2]

During evaluation of In[3]:= In[3] is: InString[2]

Out[3]= "\\(2 + 2\\)"

更新 2

在我上面的代码中用 $PreRead 替换 $Pre ,我相信你会接近你想要的:

Replace $Pre with $PreRead in my code above and you get close to what you want, I believe:

In[1]:= $PreRead = Function[{x}, Print[Names["`*"]]; x, HoldFirst]

Out[1]= Function[{x}, Print[Names["`*"]]; x, HoldFirst]

In[2]:= a = 1

During evaluation of In[2]:= {x}

Out[2]= 1

In[3]:= b = 2

During evaluation of In[3]:= {a,x}

Out[3]= 2

*Value 级别拦截 In 是不可能的,因为内核根本没有通过top"中的值操作与 In 交互-level" Mathematica 代码.

It's not possible to intercept In at the *Value level because the Kernel is simply not interacting with In via value manipulation in "top-level" Mathematica code.

这篇关于如何拦截为 In 变量分配新值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 05:35