我使用的是Dr.Racket,中级学生和Lambda。我想知道是否有任何方法可以简化这段代码,比如lambda、抽象、映射、过滤器等等。
; DRAWING FUNCTIONS
; draw-rocket: rocket scene --> scene
; Purpose: To draw the given rocket in the given scene
(define (draw-rocket a-rocket a-scene)
(place-image rocket-img a-rocket ROCKET-Y a-scene))
; draw-alien: alien scene --> scene
; Purpose: To draw the given alien in the given scene
(define (draw-alien an-alien a-scene)
(place-image alien-img
(posn-x an-alien)
(posn-y an-alien)
a-scene))
; draw-aliens: loa scn --> scene
; Purpose: To draw the aliens in the given scene
(define (draw-aliens a-loa scn)
(cond [(empty? a-loa) scn]
[else (draw-alien (first a-loa) (draw-aliens (rest a-loa) scn)
)]))
;
; draw-shot: shot scene --> scene
; Purpose: To draw the given shot in the given scene
(define (draw-shot a-shot scn)
(place-image SHOT-IMG (posn-x a-shot) (posn-y a-shot) scn))
; draw-aliens: loa scn --> scene
; Purpose: To draw the aliens in the given scene
(define (draw-shots a-los scn)
(cond [(empty? a-los) scn]
[else (draw-shot (first a-los) (draw-shots (rest a-los) scn)
)]))
; draw-world: world --> scene
; Purpose: Draw the world in the empty scene
(define (draw-world a-world)
(draw-rocket (world-rocket a-world)
(draw-aliens (world-aliens a-world)发布于 2014-07-18 18:02:39
在这方面有一些重大问题:
; draw-rocket: rocket scene --> scene
; Purpose: To draw the given rocket in the given scene
(define (draw-rocket a-rocket a-scene)
(place-image rocket-img a-rocket ROCKET-Y a-scene))为什么不为其他人绘制代码的模式呢?使用(pos火箭),(pos火箭)代替-火箭-Y.这将有助于您稍后抽象代码。
; draw-aliens: loa scn --> scene
; Purpose: To draw the aliens in the given scene
(define (draw-shots a-los scn)
(cond [(empty? a-los) scn]
[else (draw-shot (first a-los) (draw-shots (rest a-los) scn)
)])) 这种方法有错误的目的和签名。这应该是:
; draw_shots: los scn --> scn
; Purpose: To draw the shots in the given scene此代码似乎存在多个问题:
; draw-world: world --> scene
; Purpose: Draw the world in the empty scene
(define (draw-world a-world)
(draw-rocket (world-rocket a-world)
(draw-aliens (world-aliens a-world)我还认为,您希望嵌套调用,以便结果是累积的。这样做的方式如下:
; draw-world: world --> scene
; Purpose: Draw the world in the scene (why would does it have to be empty?)
(define (draw-world a-world)
(draw-shots (world-shots
(draw-rocket (world-rocket
(draw-aliens (world-aliens a-world)))))))至于使用高阶函数:
尝试像这样使用foldr:
(define (draw-shots a-los scn)
(foldr draw-shot (first a-los) (rest a-los)))类似地,您可以将其应用于列表中的所有函数。
最后,在这里使用抽象非常容易。创建一个新的类型,称为雪碧或演员或类似的东西,并有外星人,射击和火箭都扩展它。这样你只需要两个函数:一个用于单数,一个用于复数。
https://codereview.stackexchange.com/questions/37579
复制相似问题