You can use Trace
with TraceDepth
option set to 1
to get evaluation steps giving whole expression, and format result as you want it. Function performing this actions can be assigned to $Pre
to be automatically used for all inputs.
ClearAll[showSetSteps]
SetAttributes[showSetSteps, HoldAllComplete]
showSetSteps[Set[lhs_, rhs_]] :=
With[{trace = Replace[Trace[rhs, TraceDepth -> 1], {} -> {HoldForm@rhs}]},
lhs = trace[[-1, 1]];
Fold[HoldForm@Set[#2, #1] &, Append[Reverse@trace, HoldForm@lhs]]
]
showSetSteps[expr_] := expr
$Pre = showSetSteps;
Which will give:
a = 1
b = 2
x = a + b
(* a = 1 *)
(* b = 2 *)
(* x = 1 + 2 = 3 *)
Depending on what you actually expect to see in the result, you might want to use something else than Trace
, for example something based on Inactivate
/Activate
.
ClearAll[inactivateActivate]
SetAttributes[inactivateActivate, HoldFirst]
inactivateActivate[expr_, patt_: _, opts : OptionsPattern[]] :=
Inactivate[expr, patt, opts] // Evaluate // HoldForm // Activate //
{#, # // ReleaseHold} &
Which gives:
a = 1; b = 2; c = 3; d = 4;
Trace[(a + b) c^d, TraceDepth -> 1]
inactivateActivate[(a + b) c^d]
(* {3*81, 243} *)
(* {(1 + 2) 3^4, 243} *)
f[x_] := x^2 + 10
Trace[(a + b) f[c] - c, TraceDepth -> 1]
inactivateActivate[(a + b) f[c] - c]
inactivateActivate[(a + b) f[c] - c, h_ /; Context[h] === "System`"]
(* {57 - 3, 54} *)
(* {(1 + 2) f[3] - 3, 54} *)
(* {(1 + 2) 19 - 3, 54} *)
13 + 14
without assigning 13 and 14 to variables? Still13 + 14 = 27
? $\endgroup$