试图完成Conway's Game of Life in Racket的实现,我正在为所有内容添加类型。我有麻烦弄清楚我究竟需要做什么才能从gui库中正确键入类。
(: new-timer (Instance Timer%))
(define new-timer (new timer% [interval 400]
[notify-callback (lambda () (begin
(set-field! grd cv (next-grid (get-field grd cv) ROW COLUMNS))
(send cv on-paint)))]))
(: new-canvas% Canvas%)
(define new-canvas% (class canvas%
(super-new)
(inherit get-dc suspend-flush resume-flush)
(field [dc : (Instance DC<%>) (get-dc)] [grd : Grid (make-grid ROW COLUMNS)])
(define/override (on-char char)
(let ([event (send char get-key-code)])
(cond
[(and (char? event) (char=? event #space)) (send new-timer stop)])))
(define/override (on-paint)
(send dc erase)
(suspend-flush)
(render-grid grd ROW COLUMNS dc)
(resume-flush))))
(: cv (Instance Canvas%))
(define cv (new new-canvas% [parent main-frame]))
我在
下面得到这个错误/Documents/conways-game-of-life/main.rkt:49:83: Type Checker: type mismatch;
; the object is missing an expected field
; field: grd
; object type: (Instance Canvas%)
; in: (get-field grd cv)
; Context:
; /usr/share/racket/collects/racket/promise.rkt:128:5
; /home/diego/Documents/conways-game-of-life/main.rkt:49:53: Type Checker: type mismatch;
; expected an object with field grd
; given: (Instance Canvas%)
; in: (set-field! grd cv (next-grid (get-field grd cv) ROW COLUMNS))
我认为这是因为画布通常没有一个网格域,但每次我试图给我的画布类型声明(: cv (Instance new-canvas%))
它说它是未绑定的。完整的文件和所有的代码可以在这里找到。有人有什么想法吗?
在new-timer
的定义中,您试图获得cv
的grd
字段。
虽然cv
是类new-canvas%
的实例,但它的类型不包含该字段。您需要为new-canvas%
创建一个新的Class
类型。按照惯例,它应该是一个大写的版本,如New-Canvas%
。
(define-type New-Canvas% (Class ....))
(: new-canvas% New-Canvas%)
(define new-canvas% (class ....))
(: cv (Instance New-Canvas%))
(define cv (new .....))
使用Class
定义的New-Canvas%
类型应该指定新字段grd
,并指定它是Canvas%
的子类。