2017-03-06 72 views
2

有沒有辦法從Common Lisp的通用函數中提取方法列表?
例如:Common Lisp:從通用函數中提取方法

(defmethod say ((self string)) ; method-0 
    (format t "Got string: ~a~%" self)) 

(defmethod say ((self integer)) ; method-1 
    (format t "Got integer: ~a~%" self)) 

(defmethod say ((self symbol)) ; method-2 
    (format t "Got symbol: ~a~%" self)) 

(extract-methods-from-generic 'say) ; -> (method-0-obj method-1-obj method-2-obj) 

更具體地講,我針對ECL,所以如果這可以通過C API來完成 - 這是確定。
我需要這個做下一招:

(defgeneric merged-generic()) 

(loop for method 
     in (extract-methods-from-generic 'some-generic-0) 
     do (add-method merged-generic method)) 
(loop for method 
     in (extract-methods-from-generic 'some-generic-1) 
     do (add-method merged-generic method)) 

回答

4

通用功能generic-function-methods在CLOS可以得到一個泛型函數(見CLOS protocol)的所有方法,但要注意的是,對於第二部分你的問題,你可以附加一個方法的通用函數(add-method)僅當該方法是從任何其他通用功能分離(見protocol):

的錯誤也暗示,如果該方法已經與某些其他通用功能相關聯。

你可以通過包closer-mop同時使用這些功能,獨立於任何實現:

CL-USER> (ql:quickload "closer-mop") 
("closer-mop") 
CL-USER> (in-package :closer-mop) 
#<Package "CLOSER-MOP"> 
C2MOP> (defgeneric say (x)) 
#<COMMON-LISP:STANDARD-GENERIC-FUNCTION SAY #x30200176712F> 
C2MOP> (defmethod say ((self string)) ; method-0 
    (format t "Got string: ~a~%" self)) 

(defmethod say ((self integer)) ; method-1 
    (format t "Got integer: ~a~%" self)) 

(defmethod say ((self symbol)) ; method-2 
    (format t "Got symbol: ~a~%" self)) 
#<COMMON-LISP:STANDARD-METHOD SAY (SYMBOL)> 
C2MOP> (generic-function-methods #'say) 
(#<COMMON-LISP:STANDARD-METHOD SAY (SYMBOL)> #<COMMON-LISP:STANDARD-METHOD SAY (INTEGER)> #<COMMON-LISP:STANDARD-METHOD SAY (STRING)>) 
C2MOP> (defgeneric merged-generic (x)) 
#<COMMON-LISP:STANDARD-GENERIC-FUNCTION MERGED-GENERIC#x30200181B74F> 
C2MOP> (add-method #'merged-generic (first **)) 

#<COMMON-LISP:STANDARD-METHOD SAY (SYMBOL)> is already a method of #<COMMON-LISP:STANDARD-GENERIC-FUNCTION SAY #x30200165863F>. 
    [Condition of type SIMPLE-ERROR] 
; Evaluation aborted on #<SIMPLE-ERROR #x3020016719FD>. 
CL-USER> (let ((first-method (first (generic-function-methods #'say)))) 
      (remove-method #'say first-method) 
      (add-method #'merged-generic first-method)) 
#<COMMON-LISP:STANDARD-GENERIC-FUNCTION MERGED-GENERIC#x302000DC54DF> 
CL-USER> (merged-generic "a string") 
Got string: a string 
NIL 
+0

好了,但有可能「克隆」的方法及複印件連接到另一個通用功能? – AlexDarkVoid

+0

你可以看看這個問題的答案:http://stackoverflow.com/questions/11067899/is-there-a-generic-method-for-cloning-clos-objects – Renzo

+0

@Renzo這clonig一個對象。他想在兩種通用方法之間進行合併而不破壞原文,這是在這個答案中完成的。也許人們可以以某種方式代理它? – Sylwester