2014-08-30 38 views
0

我是Racket的新手。我试图从here的问题1。以下是我可以让代码:在Racket中使用struct

#lang racket 

(require 2htdp/image) 

(require rackunit) 
(require rackunit/text-ui) 
(require "extras.rkt") 

(define curr-dir "n") 
(define curr-x 30) 
(define curr-y 40) 

;; Structure that I thought about 
(define-struct robot (x y direction)) 
(define irobot (make-robot curr-x curr-y curr-dir)) 

(define MAX_HEIGHT 200) 
(define MAX_WIDTH 400) 

(define (render-robot) 
(place-image 
(crop 14 0 10 20 (circle 10 "solid" "blue")) 
19 10 
(circle 10 "solid" "red")) 
) 

(define (spawn-robot x y direction) 
(place-image 
(cond 
    [(string=? "n" direction) (rotate 90 (render-robot))] 
    [(string=? "e" direction) (render-robot)] 
    [(string=? "w" direction) (rotate 180 (render-robot))] 
    [(string=? "s" direction) (rotate 270 (render-robot))] 
    ) 
x y 
(empty-scene MAX_WIDTH MAX_HEIGHT) 
) 
) 

(define (initial-robot x y) 
(if (and (<= x (- MAX_HEIGHT 10)) (<= y (- MAX_WIDTH 10))) 
    (spawn-robot x y curr-dir) 
    (error "The placement of the robot is wrong!") 
    ) 
) 

(define robot1 (initial-robot curr-x curr-y)) 

;;-----------------------------------------------------;; 

;; Doubt Here (Make the robot turn left) 
(define (robot-left robot-obj) 
(set! curr-dir "w") ;; Hard coded for north direction 
(initial-robot curr-x curr-y) 
) 

;; Doubt Here (Function checks whether robot is facing north or not.) 
(define (robot-north? robot-obj) 
(if (string=? "n" curr-dir) (true) (false)) 
) 

在解释我尝试了这一点:

Interpreter Snap

我在想,代码可能会很好,但还是有些疑虑冒出我的脑海里:

  1. 在代码根据我使用的结构(使-结构)应 一直不错,但accordin克来解释我认为 问题的机器人实例是功能initial-robot的结果。 使用结构是否可行?

  2. 在功能robot-leftrobot-north?我应该如何使用 robot1作为参数?设置存储对象当前方向的全局变量可用于提到的功能 。我应该在这里做什么?

任何建议是值得欢迎的。 谢谢!

+0

大家知道,这个问题更适合于http://codereview.stackexchange.com/ – 2014-08-30 19:41:57

回答

2

你是正确的,一个结构将是一个更好的选择:

1)你不会被局限于在你的代码的单个机器人和

2)你会在功能进行编程方式,这是任务所需要的。

所以,用你的机器人结构:

(define-struct robot (x y direction)) 

确保你给一个适当的数据定义的结构。

;; A Robot is a (make-robot x y direction), where: 
;; - x is an integer 
;; - y is an integer 
;; - direction is a string 

虽然,我建议使用符号而不是字符串direction


(robot-left)

;; Turns a robot to the left. 
;; Robot -> Robot 
(define (robot-left robot-obj) 
    (make-robot (robot-x robot-obj) 
       (robot-y robot-obj) 
       "w")) 

(robot-north?)

;; Does robot-obj face north? 
;; Robot -> Boolean 
(define (robot-north? robot-obj) 
    (string=? (robot-direction robot-obj) "n")) 

现在,将这些功能集成到你的代码,你需要确保你分开数据的想法并输出您目前没有的图像。

(initial-robot)根本不应该渲染。它应该只返回一个机器人的实例,如我们的数据定义中所定义的那样。

请注意,在此作业赋予的规范不需要要求您完成渲染。这将是一个单独的承诺。他们要求您定义的所有功能都严格处理数据。之后,您可以考虑渲染以可视化方式测试您的功能,作为单元测试的额外补充,您还应该为每个功能创建。

我提供给你的代码应该是一个很好的起点,可以帮助你弄清楚如何设计其余的函数。直到最后,不要担心渲染!不要忘记,在家庭作业中给出的每个签名都提到了Robot,它引用了我们为机器人结构创建的数据定义。