首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >CLOS:任意函数相结合的方法

CLOS:任意函数相结合的方法
EN

Stack Overflow用户
提问于 2018-07-22 21:26:56
回答 1查看 276关注 0票数 2

在阅读CLOS时(在Paul的ANSI中),我注意到有九个函数可以给defmethod作为第二个参数:+andappendlistmaxminnconcorprogn。根据这个答案的说法,它们被称为简单的方法组合。

问题

为什么只有这九个?为什么我不能把任意的函数作为第二个论点呢?

我想要的例子

假设我将xor定义为

代码语言:javascript
复制
(defun xor (&rest args)
   (loop for a in args counting (not (null a)) into truths
      finally (return (= truths 1))))

(这当然可以改进)。我想用xor定义几个描述衣服及其组合的类

代码语言:javascript
复制
(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来指导我应该穿什么:

代码语言:javascript
复制
> (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

我清楚知道,这是一个不具实际重要性的相当人为的例子。不过,我想知道背后是否有更深层次的原因,或对这九项功能的限制是否只是为了使实现更容易。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-07-22 22:32:57

使用标准的Common宏定义-方法-组合定义您自己的简单方法组合

示例:

代码语言:javascript
复制
(define-method-combination xor :identity-with-one-argument t)

然后:

代码语言:javascript
复制
CL-USER 5 > (mapcar #'looks-cool (list (make-instance 'too-stiff)
                                       (make-instance 'scottish)
                                       (make-instance 'also-good)
                                       (make-instance 'too-crazy)))
(NIL T T NIL)

如果我们看一下(define-method-combination xor :identity-with-one-argument t),它对xor这个名字有几个含义

  • 它使用运算符xor --一个函数、宏或特殊形式--不仅允许函数。如果操作符名称与方法组合名称->不同,则使用:operator关键字指定该名称。
  • 它定义了一个名为xor的方法组合。这个名称可以在defgeneric中使用。
  • 它定义了一个方法限定符xor。这可以在defmethod中使用。

请注意,还可以使用该DEFINE-METHOD-COMBINATION定义更复杂的方法组合。

票数 7
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51469397

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档