1

我正在尝试通过另一个结构实例或其名称访问结构实例的字段。诚然,这听起来很令人困惑,我有一个(非常构造的)示例:

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

我有实例hitchikers-guide。如果我想查找其作者的所有书籍,我可以输入 REPL(author-books douglas-adams)并获得他所有书籍的列表。但是,如果我输入

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

或者

(author-books (first authors))

我收到错误消息:

值 DOUGLAS-ADAMS 不是预期的 AUTHOR 类型。

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

4

3 回答 3

5

您的变量authors包含symbols,而不是authors。

尝试

(defparameter authors (list douglas-adams pterry))

而是(当然,如果pterry已经定义)。

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

您需要使用symbol-value来获取相应的author.

于 2013-06-26T17:19:12.420 回答
4

如果要通过符号作为标识符来查找对象,则需要为此使用数据结构。

简单的版本是在包中使用符号。

(defun find-object (name)
  (symbol-value name))

(defun intern-object (object name)
  (setf (symbol-value name) object))

但您也可以使用哈希表:

(defvar *my-objects* (make-hash-table))

(defun find-object (name)
  (gethash name *my-objects*))

(defun intern-object (object name)
  (setf (gethash name *my-objects*) object))
于 2013-06-26T17:41:15.650 回答
1

哪个先出现——作者还是书?

;; first the author
(defstruct (author :conc-name make-author-internal)
  (name nil)
  (books '())
  (years '()))

(defun make-author (name years)
  (make-author-internal :name name :books '() :years years))

(defun author-add-book (author book)
  (setf (author-books author)
        (cons book (author-books author))))

;; now the book, requires an author (assumes one, if >1, use a list)
(defstruct (book :conc-name make-book-internal)
  (name nil)
  (author nil)
  (copy-sold '()))

(defun make-book (name author copy-sold)
  (let ((book (make-book-internal :name name :author author ...)))
    (author-add-book author book)
    book))

 ;; ...

 (defparameter douglas-adams
   (make-author "Douglas Adams" ...))

 (defparameter hitchikers-guide
   (make-book "Hitchikers-Guide" douglas-adams ...))
于 2013-06-26T21:43:30.210 回答