Skip to main content
12 of 32
added 6 characters in body
faysou
  • 11k
  • 3
  • 50
  • 131

Is it possible to Print expressions in reverse order?

Let's say I'm debugging a program step by step and want to Print some expressions (using ShowIt, for example).

Is there a way to output the result of Print on top of already printed expressions instead of at the bottom?

EDIT

For the record, this version of ShowIt is particularly useful, it can be used in conjunction with ReapTags defined here http://stackoverflow.com/a/6245166/884752. To see the list of keys defined in the debugSymbol containing the results extracted from a program you can use the function Keys defined in the same post or here http://mathematica.stackexchange.com/a/999/66. I've also incorporated the answer of Szabolcs into ShowIt.

SetAttributes[System`ShowIt, HoldAll];
System`ShowIt[expr__] := System`ShowIt[{expr}];
System`ShowIt[expr_] :=
    With[{evaluatedExpr = expr},
        (*Message[Debug::ShowIt,Defer[expr = evaluatedExpr]];*)
        If[TrueQ@$ShowIt,
     If[TrueQ@$ReverseIt,
                insertBelowEvaluationCell[Defer[expr = evaluatedExpr]];
                ,
                Print[Defer[expr = evaluatedExpr]];
            ];
        ];
        
        If[TrueQ@$SowIt,
    Sow[
    evaluatedExpr
    ,
            (*we replace $xxx with "" for expressions involving Module variables*)
                ToString@Unevaluated@expr // StringReplace[#,"$"~~Longest[DigitCharacter ..]->""]&
            ];
        ];
        
        evaluatedExpr
    ]; 

(*Debug::ShowIt = "`1`";*)
SetAttributes[System`ShowItList, {HoldAll,Listable}];
System`ShowItList[expr__]:=System`ShowItList[{expr}];
System`ShowItList[expr_] := System`ShowIt[expr];

SetAttributes[ReapTags,HoldFirst];
ReapTags[expr_]:=
   Module[{elements},
      Reap[expr,_,(elements[#1]=If[Length@#2==1,First@#2,#2])&];
      elements
   ];

Example

$ShowIt=True; $SowIt = True; $ReverseIt=False;
debugResult = ReapTags[x={1,2};y=3;z=4;ShowIt@Mean@x;ShowIt@z;ShowItList[x,y];ShowItList@{x,y};];
debugResult["Mean[x]"]
debugResult["x"]
debugResult["y"]
debugResult["z"]

The argument of ReapTags can be any expression including the call to a function which is hard to split into simple pieces thus using Reap and Sow as underlying functions is useful in such case.

faysou
  • 11k
  • 3
  • 50
  • 131