下面的代码在常见的lisp中工作,但在emacs lisp中,它会抱怨“(错误”方法参数中的未知类类型orc“)”。为什么以及如何在emacs lisp中修复它?感谢。
(defun randval (n)
(1+ (random (max 1 n))))
(defstruct monster (health (randval 10)))
(defstruct (orc (:include monster)) (club-level (randval 8)))
(defmethod monster-show ((m orc))
(princ "A wicked orc with a level ")
(princ (orc-club-level m))
(princ " club"))
答案 0 :(得分:3)
事情是...... defmethod需要它成为一个类,而不是结构,eLisp中的结构只是向量。也许您可以提出自己的通用调度方法,但可能只是使用类而不是结构将解决它 - 类在eieio.el中实现,因此您可以查看它的内部并查看它们如何进行调度。或者您可以简单地使用它:
(defun foo (monster)
(cond
((eql (aref monster 0) 'cl-orc-struct) ...) ; this is an orc
((eql (aref mosnter 0) 'cl-elf-struct) ...) ; this is an elf
(t (error "Not a mythological creature"))))
这实际上取决于那里有多少类生物,可能你会想出一些隐藏条件的宏,或者更确切地说是根据类型标签等返回调用的函数。
下面是一个简化的想法,用于制作您自己的泛型,以防您想要坚持使用结构,并且您不需要很多功能或者很乐意自己实现它:
(defvar *struct-dispatch-table* (make-hash-table))
(defun store-stuct-method (tag method definition)
(let ((sub-hash
(or (gethash method *struct-dispatch-table*)
(setf (gethash method *struct-dispatch-table*)
(make-hash-table)))))
(setf (gethash tag sub-hash) definition)))
(defun retrieve-struct-method (tag method)
(gethash tag (gethash method *struct-dispatch-table*)))
(defmacro define-struct-generic (tag name arguments)
(let ((argvals (cons (caar arguments) (cdr arguments))))
`(defun ,name ,argvals
(funcall (retrieve-struct-method ',tag ',name) ,@argvals))))
(defmacro define-struct-method (name arguments &rest body)
(let* ((tag (cadar arguments))
(argvals (cons (caar arguments) (cdr arguments)))
(generic))
(if (fboundp name) (setq generic name)
(setq generic
`(define-struct-generic
,tag ,name ,arguments)))
(store-stuct-method
tag name
`(lambda ,argvals ,@body)) generic))
(define-struct-method test-method ((a b) c d)
(message "%s, %d" a (+ c d)))
(test-method 'b 2 3)
"b, 5"