Common Lisp中的跨包defgeneric/defmethod?

Dam*_*amg 4 lisp common-lisp clos

在包中定义泛型的正确方法是什么,并在CLOS的包B中为此泛型提供方法?

先感谢您!

例:

(defpackage :common (:use :cl))  
(in-package :common)  
(defgeneric compare (a b))

(defmethod compare ((a number) (b number))  
  (cond ((< a b) -1)
        ((= a b) 0)
        (T 1)))

(defpackage :a (:use :cl))  
(in-package :a)  

(defclass foo (a b))

(defmethod compare ((x foo) (y foo)) ...)   
; SBCL isn't able to access this method via the common package
Run Code Online (Sandbox Code Playgroud)

Rai*_*wig 8

方法和函数不属于包.符号属于包.

(defpackage :common (:use :cl))  
(in-package :common)  
(defgeneric compare (a b))

(defmethod compare ((a number) (b number))  
  (cond ((< a b) -1) ((= a b) 0) (T 1)))

(defpackage :a (:use :cl))  
(in-package :a)  

(defclass foo (a b))
Run Code Online (Sandbox Code Playgroud)

如果A是当前包,那么您需要编写common :: compare来访问包COMMON的非导出符号COMPARE.

(defmethod common::compare ((x foo) (y foo)) ...)   
Run Code Online (Sandbox Code Playgroud)

如果已从包COMMON导出COMPARE,那么您可以编写:

(defmethod common:compare ((x foo) (y foo)) ...)   
Run Code Online (Sandbox Code Playgroud)

如果从包COMMON导出COMPARE并且包A将'使用'包COMMON,那么你可以写:

(defmethod compare ((x foo) (y foo)) ...)   
Run Code Online (Sandbox Code Playgroud)