按名称访问结构实例

mar*_*tin 1 lisp common-lisp

我试图通过另一个结构实例或其名称访问结构实例的字段.因为这听起来非常令人困惑,我有一个(非常构造的)例子:

(defstruct author
  (name nil)
  (books '())
  (years '()))

(defstruct book
  (name nil)
  (author '())
  (copy-sold '()))

(defparameter hitchikers-guide
  (make-book :name "Hitchikers-Guide"
             :author '(douglas-adams)
             :copy-sold '(a lot)))

(defparameter douglas-adams
  (make-author :name "Douglas Adams"
               :books '(Hitchikers-guide restaurant life-and-universe fish)
               :years '(too few)))

(defparameter authors
  '(douglas-adams pterry))
Run Code Online (Sandbox Code Playgroud)

我有实例hitchikers-guide.如果我想查找其作者的所有书籍,我可以输入REPL (author-books douglas-adams),我会得到他所有书籍的清单.但是,如果我进入

(author-books (first (book-author hitchikers-guide)))

要么

(author-books (first authors))

我收到错误消息:

值DOUGLAS-ADAMS不是预期类型AUTHOR.

我做错了,还是没办法以这种方式访问​​这些字段?

sds*_*sds 5

你的变量authors包含symbols,而不是authors.

尝试

(defparameter authors (list douglas-adams pterry))
Run Code Online (Sandbox Code Playgroud)

相反(如果,pterry已经定义了cource ).

同样,(book-author hitchikers-guide)symbols 的列表,而不是authors.

你需要用来symbol-value获得相应的author.