5

下面的代码在 common 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"))
4

1 回答 1

2

问题是...... 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"
于 2012-06-10T12:33:05.127 回答