Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

common-lisp

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

like image 285
RAbraham Avatar asked Apr 06 '14 19:04

RAbraham


3 Answers

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))))
like image 50
Frank Zalkow Avatar answered Nov 10 '22 23:11

Frank Zalkow


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.

like image 3
sds Avatar answered Nov 11 '22 00:11

sds


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.

like image 2
Ehvince Avatar answered Nov 11 '22 00:11

Ehvince