Want to return name of last defined variable without explicitly naming it
I think there must be a better way to accomplish the OP's ultimate goal than the general approach outlined above. But be that as it may, the following culls all the Set[]
commands from the last input line (so it has a little broader scope than what was asked for).
lastInputSets[] := Block[{Set},
Grid@Cases[Hold[In[#]] &[$Line - 1] /. DownValues[In],
Set[lv_, v_] :> {HoldForm[lv], ": ", lv}, Infinity]
];
Examples:
foo = 10; murf = 20 + 30;
lastInputSets[]
The OP's example:
dec = 7.1 + 6.6 + 27.2 + 66.5;
lastInputSets[]
jan = 7.1 + 6.6 + 27.2 + 66.5 + 65.7;
lastInputSets[]
feb = 7.1 + 6.6 + 27.2 + 66.5 + 65.7 + 69.7;
lastInputSets[]
Or all at once:
(dec = 7.1 + 6.6 + 27.2 + 66.5;
jan = 7.1 + 6.6 + 27.2 + 66.5 + 65.7;
feb = 7.1 + 6.6 + 27.2 + 66.5 + 65.7 + 69.7;)
lastInputSets[]
If these symbols are newly defined, you could do
$NewSymbol = (lastsymbol = #) &;
dec = 7.1 + 6.6 + 27.2 + 66.5;
Print[lastsymbol, ": ", %]
jan = 7.1 + 6.6 + 27.2 + 66.5 + 65.7;
Print[lastsymbol, ": ", %]
feb = 7.1 + 6.6 + 27.2 + 66.5 + 65.7 + 69.7;
Print[lastsymbol, ": ", %]
dec: 107.4
jan: 173.1
feb: 242.8
In response to the comment -- as a more general purpose tool, one could use $PrePrint
to automatically print the input and output from each evaluation. This uses Downvalues[In]
as in @MichaelE2's answer:
$PrePrint = (
Print[TraditionalForm@HoldForm[In[line] = #] /. line -> $Line /. DownValues[In]]; #
) &;
Now you have, for example:
Integrate[x^2, x]
$\int x^2 \, dx=\frac{x^3}{3}$
x^3/3
a = 2
$(a=2)=2$
2
Or you could just set the output to appear this way, without printing on a separate line, using
$PrePrint = (TraditionalForm@HoldForm[In[line] = #] /. line -> $Line /. DownValues[In]) &;
Use $PrePrint =.
to turn this off.
I agree with MichaelE2, though, that depending on why you want to do this, there's probably a better way to go about it.