我是Lisp的初学者。我有两个functions
,一个defparameter
和一个defstruct
。每当一本书传递给inputBook
时,我希望书的标题(字符串)成为defparameter
的名字。这可能吗?我试图硬编码下面的字符串,它说“MobyDick”,但我收到一个错误。这甚至可能吗?
我试图简单地使用传递给title
的参数,但是如果你试图将另一本书传递给函数,它们都被分配给title
但是最后一个传递将打印,而不是第一个,而不是两个。那么我怎么能这样做,以便我有没有列表或哈希表的那么多“书”?
如果后者不可能,我怎么能改变代码,以便为任意数量的书籍创建(唯一)defparameter
并通过getAuthor
函数访问?那有意义吗? (请参阅以下功能。)
(defstruct book()
(title) ;;title of the book, type string
(author) ;;author of the book, type string
(date)) ;; date of the book, type string or int
(defun inputBook(title author month year)
(defparameter "MobyDick" ;;I want this to use the parameter title
(make-book :title title
:author author
:date '(month year))))
(defun getAuthor (book)
(write (book-author book)))
非常感谢提前!另外,我是初学者。我一直在谷歌搜索,我在这里难过。
你可能想要一些看起来像这样的东西,而不是顶级变量的疯狂。
(defvar *books* (make-hash-table))
(defun bookp (title)
(nth-value 1 (gethash title *books*)))
(defun remove-book (title)
(remhash title *books*))
(defun book (title)
(nth-value 0 (gethash title *books*)))
(defun (setf book) (new title)
(setf (gethash title *books*) new))
然后,例如:
> (setf (book 'moby) (make-book ...))
> (book 'moby)
> (bookp 'moby)
> (remove-book 'moby)
使用具有任意名称的符号具有典型的缺点:您可以覆盖现有符号的值。因此,为它设置一个单独的包是有用的,它不会从其他包中导入符号。
更好的是拥有一个哈希表,它将从一个字符串映射到book对象。
带符号的代码草图:
(defstruct book
(title) ;; title of the book, type string
(author) ;; author of the book, type string
(date)) ;; date of the book, type list
(defun input-book (title author month year)
(setf (symbol-value (intern title))
(make-book :title title
:author author
:date (list month year))))
例:
CL-USER 52 > (input-book "Lisp Style & Design"
"Molly M. Miller, Eric Benson"
1 1990)
#S(BOOK :TITLE "Lisp Style & Design"
:AUTHOR "Molly M. Miller, Eric Benson"
:DATE (1 1990))
CL-USER 53 > (book-author (symbol-value '|Lisp Style & Design|))
"Molly M. Miller, Eric Benson"
CL-USER 54 > (book-author |Lisp Style & Design|)
"Molly M. Miller, Eric Benson"