为什么这段代码在球拍上给我一个内存错误代码?

时间:2016-09-12 21:21:21

标签: memory racket racket-student-languages

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

(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)]))

1 个答案:

答案 0 :(得分:2)

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

  

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

由于TrafficLightState一直在调用自身,它会有效地进入无限循环,消耗越来越多的内存直到它用完为止。这肯定不是你想要的,所以你应该重新考虑cond的工作方式并调整你的功能来相应地修复它。

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