Skip to content

Instantly share code, notes, and snippets.

@klieret
Last active September 19, 2021 23:11
Show Gist options
  • Save klieret/3270dd2ac254636edb1ed6ce1c085368 to your computer and use it in GitHub Desktop.
Save klieret/3270dd2ac254636edb1ed6ce1c085368 to your computer and use it in GitHub Desktop.
Print Mathematica expressions without evaluating them & use that for a handy debug print statement to print internal variables together with their names.
debugPrint::usage="Arg 1 (bool): If False, do nothing. If True and Arg 2 is \
a string, then the string is simply printed. If True and Arg 2 is not a string, then \
first the unevaluated expression is printed, followed by the evaluated expression. \
Additionally given rules influence the styling of the output.
Arg 3 (bool): Strip suffixes like $1234 (signalling internal variables)";
unevaluatedExpression::usage="Print the argument without any kind of evaluation in \
the same way it is given here as an argument
Arg 2(bool): Strip suffixes like $1234 (signalling internal variables)";
Begin["`Private`"];
SetAttributes[unevaluatedExpression,HoldFirst];
unevaluatedExpression[expr_,removeDollars_:True]:=
Module[{ff},
ff=Evaluate[MakeBoxes@expr];
If[
removeDollars,
Return@DisplayForm@ToExpression@StringReplace[ToString@FullForm@ff,RegularExpression["\\$\\w+"]->""],
Return@DisplayForm@ff
];
];
SetAttributes[debugPrint,HoldAll];
SetAttributes[debugPrint,HoldAll];
debugPrint[debug_,expr_,removeDollars_:True,style:OptionsPattern[]]:=
Module[{symbolName},
If[
Evaluate@debug===True,
Null,
Return[]
];
If[
StringQ@expr,
(*then*)
Print@Style[expr,style,FontColor->Purple];
Return[];
];
Print[
Style[unevaluatedExpression[expr,removeDollars],style,Bold,FontColor->Purple],
Style[": ",style,FontColor->Purple],
Style[ReleaseHold@expr,style,FontColor->Purple]
]
];
End[];
@klieret
Copy link
Author

klieret commented Jan 3, 2018

a few lines on how to use this can be found here: http://www.lieret.net/2018/01/03/mathematica-unevaluated/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment