Mathematica: How to prevent evaluation of In[-1]?

2019-05-08 21:46发布

问题:

When I'm trying to get last input expression in Wolfram Mathematica 5.2 using In[-1] I get evaluated output:

In[1]:= On[In]
2 + 2
In[-1]

Out[2]= 4

During evaluation of In[1]:= In::trace: In[-1] --> In[$Line-1]. >>

During evaluation of In[1]:= In::trace: In[$Line-1] --> In[2]. >>

During evaluation of In[1]:= In::trace: In[2] --> 2+2. >>

Out[3]= 4

How can I get the input expression in unevaluated form?

回答1:

You could try InString[]

In[1]:= 2 + 2
Out[1]= 4

In[2]:= InString[-1]
Out[2]= "\\(2 + 2\\)"


回答2:

Here is another way:

In[1]:= 2 + 2
With[{line = $Line - 1}, HoldForm[In[line]] /. DownValues[In]]

Out[1]= 4

Out[2]= 2+2

Edit:

This method does not work properly with Unevaluated:

In[1]:= Unevaluated[2 + 2]
With[{line = $Line - 1}, HoldForm[In[line]]] /. (DownValues[In])
Out[1]= Unevaluated[2 + 2]
Out[2]= 2 + 2

I have opened a separate question on this.