使Clos对象可以用Lisp打印 [英] Make clos objects printable in lisp

查看:124
本文介绍了使Clos对象可以用Lisp打印的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果要使普通lisp的CLOS对象可打印(可打印打印),那么除了打印和读取外,不使用其他任何方法就可以做到这一点.

If you want to make CLOS objects in common lisp printable (print readably), how do you go about doing this without using anything but print and read.

推荐答案

执行此操作至少有两个步骤,至少在我的解决方案中,但是您将需要此功能(感谢cl-prevalence的人员(警告LLGPL )

There are two parts to doing this, at least in my solution, however you will need this function (thanks to the guys at cl-prevalence for this (warn 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) ...)

Then, for reading you will need to run this piece of code, which sets up 1/2 of the syntax which is { type-of-object ((slot-name . slot-value) (slot-name . slot-value) ...)

(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)))))

使用所有这些方法时,强烈建议

A *print-readably*.另外,请注意,循环关系未经测试

A *print-readably* is highly recommended when using all these methods. Also, note that circular relationships are untested

这篇关于使Clos对象可以用Lisp打印的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆