1

我已阅读 Racket 指南 13.7.3 Parameterized Mixins

我使用参数化 Mixinsgood-eat-fish%fish%

(define fish-interface
  (interface () eat get-size))

(define fish%
  (class* object% (fish-interface)
    (init size)
    (super-new)
    (define current-size size)
    (define/public (get-size) current-size)
    (define/public (eat other)
      (set! current-size (+ current-size (send other get-size))))))

(define (good-eat-mixin member-name)
  (define eat member-name)
  (mixin () ()
    (inherit eat)
    (define/public (good-eat y)
      (eat y) (eat y))))

(define good-eat-fish%
  ((good-eat-mixin (member-name-key eat)) fish%))

当我运行代码时,会引发以下错误:

"mixin: method was referenced in definition, but is not in any of the from-interfaces
  method name: eat
  from-interfaces:"

此错误消息是否表明没有eat方法?

如果我将代码更改为

(define (good-eat-mixin member-name)
  (define eat member-name)
  (mixin (interface () eat) (interface () eat good-eat)
    (inherit eat)
    (define/public (good-eat y)
      (eat y) (eat y))))

我收到此错误:

interface: bad syntax in: interface

不幸的是,我不知道为什么

interface () eat) 

语法不好。

4

1 回答 1

1

对于第一个问题:mixin 会强制执行一些误用检查,而您会遇到它们。例如,如果你只是这样做:

(mixin () ()
  (inherit eat)
  (define/public (good-eat y)
    (eat y) (eat y)))

然后系统检测到代码正试图依赖一个eat不属于 mixin 声明的接口的方法。您的第二次尝试更接近,但您需要额外的括号。例如,从

(mixin (interface () eat) (interface () eat good-eat)
  (inherit eat)
  (define/public (good-eat y)
    (eat y) (eat y)))

到:

(mixin ((interface () eat)) ((interface () eat good-eat))
  (inherit eat)
  (define/public (good-eat y)
    (eat y) (eat y)))

为接口命名,以便更容易看到:

(define eater<%> (interface () eat))
(define good-eater<%> (interface () good-eat))
...
(mixin (eater<%>) (good-eater<%>)
  ...)

这是一个例子:

#lang racket

(define eater<%> (interface () eat))
(define good-eater<%> (interface () good-eat))

(define fish%
  (class* object% (eater<%>)
    (init size)
    (super-new)
    (define current-size size)
    (define/public (get-size) current-size)
    (define/public (eat other)
      (set! current-size (+ current-size (send other get-size))))))

(define fish-interface
  (interface () eat get-size))

(define good-eat-mixin
  (mixin (eater<%>) (good-eater<%>)
    (inherit eat)
    (super-new)
    (define/public (good-eat y)
      (eat y) (eat y))))

(define good-eat-fish%
  (good-eat-mixin fish%))

(define f1 (new good-eat-fish% [size 42]))
(define f2 (new good-eat-fish% [size 16]))
(send f1 eat f2)
(send f1 good-eat f2)
(send f1 get-size)

(我从你的例子中去掉了成员键的东西,只是为了简化。)

我相信里面的阶级制度racket/class是名义上的而不是结构上的。

于 2013-04-16T19:48:35.730 回答