Sorry for my late reply. It's been a busy past week, and I've had several things to attend to before I could take up Lisp again.
Ramarren wrote:lispamour wrote:Is there a way to make this work in Common Lisp, short of manually iterating through the contents of the hash table and printing each key and value:
What other solution would you expect? The standard specify no representation for hashtables, and internal implementation representation would be likely non-contiguous even if you could access it. You have to print it out pair by pair.
Originally, I was hoping that a hashtable would allow me to specify a print function in the same way that a structure does. Eg:
Code: Select all
(defstruct (mystruct
(:print-function print-mystruct))
foo
bar)
That way, I could print out the keys and values pair by pair in PRINT-MYSTRUCT.
I had thought it a little strange that the PRINT function would work for structs and plists, but not for hashtables. But as you've indicated above, the PRINT function simply accesses a contiguous chunk of memory, which is not characteristic of hashtables. In Clojure, hashtables, lists, and sets are all first-class objects which comply with PRINT and READ so that they can be persisted to disk.
It is possible to create a custom read macro to make READ work on such custom representation, but there isn't really much point usually.
Can you show me how to write these PRINT and READ macros so that they call the usual PRINT and READ functions for structs and plists, but for hashtables, they call the custom hash-printing and hash-reading functions:
Code: Select all
(defun print-hash (hashtable output-stream)
(with-standard-io-syntax
(print (hash-table-count hashtable) output-stream)
(maphash #'(lambda (k v)
(print k output-stream)
(print v output-stream))
hashtable)))
Code: Select all
(defun read-hash (input-stream)
(let ((hnew (make-hash-table))
(n 0))
(with-standard-io-syntax
(setf n (read input-stream))
(dotimes (i n)
(setf (gethash (read input-stream) hnew) (read input-stream))))
hnew))
Ie, is it possible in the PRINT macro to call the usual PRINT function for plists and structs, but PRINT-HASH for hashtables without causing a name collision between the function PRINT and the macro PRINT?