试图理解为什么DrRacket突出了我的一些cond条款

Mic*_*aya 1 racket

第二版" 如何设计程序"中的练习42 解释了DrRacket突出显示了cond下面代码中的最后两个子句,因为测试用例并未涵盖所有可能的情况.

; TrafficLight -> TrafficLight
; given state s, determine the next state of the traffic light

(check-expect (traffic-light-next "red") "green")

(define (traffic-light-next s)
  (cond
    [(string=? "red" s) "green"]
    [(string=? "green" s) "yellow"]
    [(string=? "yellow" s) "red"]))
Run Code Online (Sandbox Code Playgroud)

我的理解是else最后的一个条款应该涵盖其余的案例,所以我尝试替换最后的表达式:

(define (traffic-light-next s)
  (cond
    [(string=? "red" s) "green"]
    [(string=? "green" s) "yellow"]
    [(string=? "yellow" s) "red"]
    [else "green"]))
Run Code Online (Sandbox Code Playgroud)

这并不能解决突出问题.这里发生了什么?

Asu*_*awa 5

我想你可能会误解突出的目的.代码覆盖工具的要点是确保您有足够的测试用例(即check-expects)来覆盖您编写的所有代码,而不是确保您的cond子句涵盖数据定义的所有情况.在您的代码段中,您check-expect只是在测试"red"案例.您可以通过check-expect为数据定义的其他两种情况编写s来消除突出显示.

另请注意,您实际上不想在else此处写一个案例,因为您的数据定义TrafficLight仅包含三种情况.在else不违反签名/合同的情况下,您无法测试您的案例.