结构对象转换为plist

结构对象转换为plist

本文介绍了常见的LISP:将(未知)结构对象转换为plist?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

(defstruct (mydate (:constructor make-mydate (year month day)))
  (year 1970)
  (month 1)
  (day 1))

 (defvar *date1* (make-mydate 1992 1 1))

这个问题更普遍,但是说我想将像 date1 这样的对象转换为文档",我可以将其持久化到数据库(例如mongoDB,使用包cl-mongo).所以我写

The problem is more general, but say I would like to convert an object like date1 to a "document" I can persist to a database (e.g. mongoDB, using package cl-mongo). So I write

(defun mydate->document (mydate)
   (cl-mongo:$ (cl-mongo:$ "year" (mydate-year mydate))
               (cl-mongo:$ "month" (mydate-month mydate))
               (cl-mongo:$ "day" (mydate-day mydate))))

REPL--> (mydate->doc *date1*)
kv-container : #(#S(CL-MONGO::PAIR :KEY year :VALUE 1992)
                 #S(CL-MONGO::PAIR :KEY month :VALUE 1)
                 #S(CL-MONGO::PAIR :KEY day :VALUE 1))

但是我可以不必通过编程来获取结构的所有字段,而可以通过编程获得它们的名称和值吗?毕竟,我的lisp运行时可以做到这一点:

But could I, instead of having to write down all fields of my struct, obtained their names and values programmatically? After all, my lisp runtime can do that:

REPL--> (describe *date1*)
#S(MYDATE :YEAR 1992 :MONTH 1 :DAY 1)
  [structure-object]

Slots with :INSTANCE allocation:
YEAR   = 1992
MONTH  = 1
DAY    = 1

另一方面,我在任何书中都没有找到任何相关的内容,并且我注意到cl-json库无法将结构转换为JSON格式(即使它确实转换了列表和CLOS对象).我猜想,如果有一个将结构转换为plist的函数,问题将得到解决.

On the other hand, I did not find anything relevant in any book, and I noticed that the library cl-json cannot convert structs to JSON format (even though it does convert lists and CLOS objects). I guess that if there was a function to convert a struct to a plist, the problem would be solved.

推荐答案

没有可移植的方法.

实施方式有所不同.大概大多数人都有一种访问插槽名称的方法.我不清楚为什么标准中缺少这种功能.

Implementations do it differently. Probably most have a way to access the names of the slots. It's not clear to me why such functionality is missing from the standard.

LispWorks具有:

LispWorks for example has:

(structure:structure-class-slot-names (find-class 'some-structure-class))

也许某个地方已经有一个兼容性库.对于CLOS和结构类,都应使用元对象协议功能.

Maybe there is already a compatibility library somewhere. It would make sense to use the Meta-Object Protocol functionality for CLOS also for structure classes.

SBCL:

* (sb-mop:class-slots (find-class 'foo))

(#<SB-PCL::STRUCTURE-EFFECTIVE-SLOT-DEFINITION A>
 #<SB-PCL::STRUCTURE-EFFECTIVE-SLOT-DEFINITION B>)

* (mapcar 'sb-mop:slot-definition-name *)

(A B)

这篇关于常见的LISP:将(未知)结构对象转换为plist?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 04:45