问题是...... 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"