Skip to content

Instantly share code, notes, and snippets.

@rebcabin
Created March 20, 2012 00:02
Show Gist options
  • Save rebcabin/2128704 to your computer and use it in GitHub Desktop.
Save rebcabin/2128704 to your computer and use it in GitHub Desktop.
Mathematica functions for displaying captive expressions in Grid form.
dpyNullary[ex_] :=
Grid[{{ex, ""}},
Frame -> {All,False},
Alignment -> Left,
Background -> {{LightOrange,{LightYellow}}}];
dpyMultiary[key_, vals_] :=
With[{c = Length @ vals},
Module[{
spans = Table["", {c}],
slot = Floor[(1+c)/2]},
spans[[slot]] = key;
Grid[MapThread[List,{spans, vals}],
Frame -> {All,False},
Alignment -> Left,
Background -> {{LightOrange,{LightGreen}}}]
]];
dpyAtom[ex_] :=
Grid[{{ex}},
Frame -> All,
Alignment -> Left,
Background ->
Switch[Head @ ex,
String, Green,
Symbol, LightPurple,
Integer, LightBlue,
Real, LightBlue,
Rational, LightBlue,
Complex, LightBlue,
_, Red]];
SetAttributes[gridCaptive, HoldAllComplete];
dpyCaptive[{ex_}] := dpyNullary[ex];
dpyCaptive[{a_, as__}] := dpyMultiary[a, dpyCaptive /@ {as}];
dpyCaptive[ex_?AtomQ] := dpyAtom[ex];
dpyCaptive[x___] := Throw[Unevaluated @ {x}];
gridCaptive[expr_]:= dpyCaptive @ captive @ expr;
SetAttributes[captive, HoldAll]; (* NOT HoldAllComplete *)
captive[expr_ /; AtomQ @ Unevaluated @ expr] :=
If[ValueQ @ expr, captive @ Evaluate @ expr, expr]
captive[head_[args___]] :=
{captive @ head} ~Join~ (captive /@ (Unevaluated @ {args}))
captive[x___] := Throw[{x}];
(* examples of using this *)
ClearAll[f, g, h, foo]
gridCaptive[f[x_ /; Head@Unevaluated@x === Symbol] := x]
gridCaptive[g[x_] := x /; Head@Unevaluated@x === Symbol]
gridCaptive[h[x_] /; Head@Unevaluated@x === Symbol := x]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment