【发布时间】:2018-07-22 21:26:56
【问题描述】:
在阅读关于 CLOS(在 Paul Graham 的 ANSI Common Lisp 中)时,我注意到有九个函数可以作为第二个参数传递给 defmethod:
+、and、append、list、max、min、nconc、or 和 progn。根据this answer,它们被称为简单方法组合。
问题
为什么只有这九个?我不能将任意函数作为第二个参数传递的原因是什么?
我想要的示例
假设我将xor 定义为
(defun xor (&rest args)
(loop for a in args counting (not (null a)) into truths
finally (return (= truths 1))))
(这当然可以改进)。我想使用xor定义几个描述衣服及其组合的类:
(defgeneric looks-cool (x)
(:method-combination xor))
(defclass black-trousers () ())
(defclass quilt () ())
(defclass white-shirt () ())
(defclass hawaii-shirt () ())
(defmethod looks-cool xor ((tr black-trousers)) nil)
(defmethod looks-cool xor ((qu quilt)) t)
(defmethod looks-cool xor ((ws white-shirt)) nil)
(defmethod looks-cool xor ((hs hawaii-shirt)) t)
(defclass too-stiff (black-trousers white-shirt) ())
(defclass scottish (quilt white-shirt) ())
(defclass also-good (black-trousers hawaii-shirt) ())
(defclass too-crazy (quilt hawaii-shirt) ())
现在,如果编译(它没有编译),我将能够使用 Lisp 来指导我穿什么:
> (looks-cool (make-instance 'too-stiff))
NIL
> (looks-cool (make-instance 'scottish))
T
> (looks-cool (make-instance 'also-good))
T
> (looks-cool (make-instance 'too-crazy))
NIL
我很清楚这是一个相当人为的例子,没有实际意义。不过,我想知道背后是否有一些更深层次的原因,或者对九个功能的限制是否只是为了让实现更容易。
【问题讨论】:
标签: oop common-lisp language-design clos method-combination