5

Dispatch and SparseArray have nice output forms that summarise their contents:

Example of Dispatch output

The contents even manage to be retained fully on copy/paste. How can I make this happen for my own symbols?

Dr. belisarius
  • 115,881
  • 13
  • 203
  • 453
Patrick Stevens
  • 6,107
  • 1
  • 16
  • 42

1 Answers1

9

If you want to make a nice neat way of displaying a thing with Head head, the following will work (thanks to Sjoerd):

head /: Format[b : head[a_Association]] := 
 RawBoxes[
  BoxForm`ArrangeSummaryBox[
   "NiceHeadName",
   b, 
   Graphics3D[Cone[], ImageSize -> 20],
   {BoxForm`MakeSummaryItem[{"Summary 1: ", a["sum1"]}, StandardForm], 
    BoxForm`MakeSummaryItem[{"Summary 2: ", a["sum2"]}, StandardForm]}, 
   {BoxForm`MakeSummaryItem[{"Expanded thing 1: ", a["sumhidden1"]}, StandardForm], 
    BoxForm`MakeSummaryItem[{"Expanded thing 2: ", a["sumhidden2"]}, StandardForm], 
    BoxForm`MakeSummaryItem[{"Expanded thing 3: ", a["sumhidden3"]}, StandardForm]},
   StandardForm]
 ];

If you give a definition as

head[
 <| "sum1" -> 10, "sum2" -> "Hi!",
    "sumhidden1" -> 1, "sumhidden2" -> 2, "sumhidden3" -> Pi
 |>
]

then the output (shown twice, once non-expanded in the Out cell and once expanded in the next In cell) is:

Nice output for head object

Moreover, this object has the same FullForm as the original: you can copy and paste it, and it'll still work fine. In particular, though it appears to have Head NiceHeadName, it actually still has Head head, just as required.

Dr. belisarius
  • 115,881
  • 13
  • 203
  • 453
Patrick Stevens
  • 6,107
  • 1
  • 16
  • 42
  • Could you please tell me what role b plays here? – chris Apr 07 '20 at 20:26
  • @chris If you FullForm the expression, the relevant chunk is Format[Pattern[b, head[Pattern[a, Blank[Association]]]]]. It's just a pattern name. See the docs for Pattern, and note that b_ is shorthand for b : _. – Patrick Stevens Apr 08 '20 at 07:05
  • What is the point of the b in "NiceHeadName", b, ? It seems to lead to some recursions in some situation and I do not see its benefit? – chris May 23 '20 at 14:47