1

我需要创建一个定义,根据绿色黄色或红色的字符串输出交通灯的图片,无论字符串是什么都决定了哪个灯泡是实心的

(define green-light
  (overlay (above (circle 15 "solid" "green")
                  (circle 15 "outline" "yellow")
                  (circle 15 "outline" "red"))
           (rectangle 50 100 "outline" "black")))

(define yellow-light
  (overlay (above (circle 15 "outline" "green")
                  (circle 15 "solid" "yellow")
                  (circle 15 "outline" "red"))
           (rectangle 50 100 "outline" "black")))

(define red-light
  (overlay (above (circle 15 "outline" "green")
                  (circle 15 "outline" "yellow")
                  (circle 15 "solid" "red"))
           ( rectangle 50 100 "outline" "black")))

(check-expect (TrafficLightState "green")
              (overlay (above (circle 15 "solid" "green")
                              (circle 15 "outline" "yellow")
                              (circle 15 "outline" "red"))
                       (rectangle 50 100 "outline" "black")))

(check-expect (TrafficLightState "yellow")
              (overlay (above (circle 15 "outline" "green")
                              (circle 15 "solid" "yellow")
                              (circle 15 "outline" "red"))
                       (rectangle 50 100 "outline" "black")))
(check-expect (TrafficLightState "red")
              (overlay (above (circle 15 "outline" "green")
                              (circle 15 "outline" "yellow")
                              (circle 15 "solid" "red"))
                       (rectangle 50 100 "outline" "black")))


(define (TrafficLightState color) 
  (cond [(TrafficLightState "green") (place-image green-light)]
        [(TrafficLightState "yellow") (place-image yellow-light)]
        [(TrafficLightState "red") (place-image red-light)]))
4

1 回答 1

2

问题在于您的TrafficLightState功能。如果您单击“检查语法”按钮并将鼠标悬停在 DrRacket 中的名称上,您会看到一些关于它有什么问题的提示:

所有这些箭头都指向使用TrafficLightState函数的地方,实际上,它在自身内部被使用了 3 次。也就是说,该函数正在调用自身,这称为递归函数。TrafficLightState

由于TrafficLightState不断地调用自己,它实际上进入了一个无限循环,消耗越来越多的内存,直到它耗尽。这绝对不是您想要的,因此您应该重新考虑工作方式cond并调整您的功能以相应地修复它。

使用 DrRacket 中的步进器来逐步执行程序可能会有所帮助,以便准确了解正在发生的事情。单击菜单中的“步骤”按钮,然后单击箭头以一步一步地执行程序。

于 2016-09-12T21:42:11.173 回答