使clos对象在lisp中可打印

时间:2010-06-21 16:41:32

标签: serialization lisp common-lisp clos

如果你想让普通的lisp打印CLOS对象(可读打印),你如何在不使用打印和阅读的情况下进行此操作。

1 个答案:

答案 0 :(得分:5)

这样做有两个部分,至少在我的解决方案中,但是你需要这个功能(感谢那些cl-prevalence的人(警告LLGPL

(defun get-slots (object)
  ;; thanks to cl-prevalence
  #+openmcl
  (mapcar #'ccl:slot-definition-name
      (#-openmcl-native-threads ccl:class-instance-slots
       #+openmcl-native-threads ccl:class-slots
       (class-of object)))
  #+cmu
  (mapcar #'pcl:slot-definition-name (pcl:class-slots (class-of object)))
  #+sbcl
  (mapcar #'sb-pcl:slot-definition-name (sb-pcl:class-slots (class-of object)))
  #+lispworks
  (mapcar #'hcl:slot-definition-name (hcl:class-slots (class-of object)))
  #+allegro
  (mapcar #'mop:slot-definition-name (mop:class-slots (class-of object)))
  #+sbcl
  (mapcar #'sb-mop:slot-definition-name (sb-mop:class-slots (class-of object)))
  #+clisp
  (mapcar #'clos:slot-definition-name (clos:class-slots (class-of object)))
  #-(or openmcl cmu lispworks allegro sbcl clisp)
  (error "not yet implemented"))

然后,为了阅读,你需要运行这段代码,它设置了{ type-of-object ((slot-name . slot-value) (slot-name . slot-value) ...)

的语法的1/2
(set-macro-character 
     #\{
     #'(lambda (str char)
     (declare (ignore char))
     (let ((list (read-delimited-list #\} str t)))
       (let ((type (first list))
         (list (second list)))
         (let ((class (allocate-instance (find-class type))))
           (loop for i in list do
            (setf (slot-value class (car i)) (cdr i)))
           class)))))

要进行打印,请使用

(defmethod print-object ((object standard-object) stream)
  (format stream "{ ~s ~s}" (type-of object)
      (loop for i in (get-slots object)
    collect (cons i (slot-value object i)))))

使用所有这些方法时,强烈建议使用*print-readably*。另请注意,循环关系未经测试