Common Lisp Library for Pretty Printing? e.g. pretty print a nested hash table
Asked Answered
S

3

8

I am new to common lisp. Is there a CL library to pretty print collections, in my case, nested hash tables?

Seismic answered 6/4, 2014 at 19:36 Comment(2)
Library requests are off-topic for StackOverflow, but the standard includes a very powerful pretty printing facilty, described in 22.2 The Lisp Pretty Printer. Does it not meet your needs? If so, describe your problem in more detail, please. If you're willing to use it, show the types of collections that you're talking about, and we can probably show you how to pretty print them nicely. In this case, I think you'd just copy the standard pretty print dispatch table into a new table, replace the function for printing hash…Marja
…tables, and then call it a day. You might also have a look at FSet.Marja
A
8

If you considering writing it yourself, here is a starting point using print-object. It is not implementation independent, but this works at least in LispWorks and SBCL.

(defmethod print-object ((object hash-table) stream)
  (format stream "#HASH{~{~{(~a : ~a)~}~^ ~}}"
          (loop for key being the hash-keys of object
                using (hash-value value)
                collect (list key value))))
Adenoidectomy answered 7/4, 2014 at 19:0 Comment(0)
I
3

First, CL does not have a "collection" type.

Second, some (most?) CL implementations will print hash tables with content if you set *print-array* to t.

Third, if your CL implementation does not do that, you can easily whip up your own, based on, say, hash-table->alist.

Isar answered 6/4, 2014 at 20:11 Comment(2)
Also, alexandria:hash-table-alist exists.Cnidus
With *print-array* to t, SBCL only shows #<HASH-TABLE :TEST EQL :COUNT 1 {100342D7F3}>. It is not pretty-printed with content.Evalynevan
E
2

With the Serapeum library, we can use the dict constructor and enable pretty-printing with (toggle-pretty-print-hash-table):

(dict :a 1 :b 2 :c 3)
;; =>
(dict
  :A 1
  :B 2
  :C 3
 )

With the Rutils library:

if we enable pretty printing of hash-tables with (toggle-print-hash-table), they are printed like so:

rutils-user> #h(:foo 42)
#{
  :FOO 42
 } 

It uses print-object under the hood, so its warning applies (not standard, but works in some implementations like SBCL).

The #h reader macro is a shortcut to create hash-tables.

Evalynevan answered 22/8, 2020 at 20:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.