3

After I write and evauate the following lines in Mathematica:

a = 1
b = 2
x = a + b

It will show only the result : 3. I want mathematica to show the following for my output:

x = 1 + 2 = 3

Is it capable of doing this?

There is no similarity between my post and the other. Can anyone prove that mathematica can do what I asked for?

Adi
  • 31
  • 2

1 Answers1

5

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} *)
jkuczm
  • 15,078
  • 2
  • 53
  • 84