开发者

cross-package defgeneric/defmethod in Common Lisp?

开发者 https://www.devze.com 2022-12-18 14:12 出处:网络
What is the right way to define a generic in package A and to provide a method for this generic in package B in CLOS?

What is the right way to define a generic in package A and to provide a method for this generic in package B in CLOS?

Thank you in advance!

Example:

(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


Methods and functions don't belong to packages. Symbols belong to packages.

(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))

If A is the current package, then you need to write common::compare to access the non-exported symbol COMPARE of package COMMON.

(defmethod common::compare ((x foo) (y foo)) ...)   

If COMPARE has been exported from package COMMON, then you could write:

(defmethod common:compare ((x foo) (y foo)) ...)   

If COMPARE has been exported from package COMMON and package A would 'use' package COMMON, then you could write:

(defmethod compare ((x foo) (y foo)) ...)   
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号