就像Magic-8-ball游戏一样,我正在尝试构建一个可以按以下顺序回答不同问题的模型:
如果问题为空,则产生“你没有提出问题,再试一次”,用(无答案)表示
我写下了这个问题的代码,但空案例不起作用。
也就是说,(magic-8-ball "")
应该产生“你没有问一个问题,再试一次”。
;; 8-ball-answers: (listof string)
(define 8-ball-answers (list "It is certain" "Outlook good" "Ask again later" "Outlook not so good"))
;; no-answer: string
;; Purpose: correct form of string to produce when magic-8-ball consumes empty string
(define no-answer "you did not ask a question, try again")
;;magic-8-ball: string -> string
;;Purpose: consumes a string and produces a string
;;Effects: modifies (8-ball-answers). If the string is empty, produces
;; "you did not ask a question, try again". Otherwise, changes
;; "It is certain" to "Outlook good",
;; "Outlook is good" to "Ask again later",
;; "Ask again later" to "Outlook not so good",
;; and "Outlook not so good" to "It is certain".
(define (magic-8-ball s)
(local
[
;; new-list represents the new value of the list 8-ball-answers
;; after every time the function is called.
(define next-answer (first 8-ball-answers))]
(begin
(cond [(equal? s "") no-answer]
[else (set! 8-ball-answers (append (rest 8-ball-answers)
(list next-answer)))])
next-answer)))
这是我的测试用例:
(check-expect (and (equal? (magic-8-ball "Do you love me?")
"It is certain")
(equal? (magic-8-ball "How is your life?")
"Outlook good")
(equal? (magic-8-ball "")
"you did not ask a question, try again")
(equal? (magic-8-ball "2nd0A-wmQ232.asdA?")
"Ask again later")
(equal? (magic-8-ball "No questions here")
"Outlook not so good")
(equal? (magic-8-ball "Now do you hate me?")
"It is certain"))
true))
测试应该通过,但是我没有。字符串为空时会出现问题。
谁能告诉我这是什么问题? 谢谢!
答案 0 :(得分:1)
好,你修理了空支票。现在我可以运行代码:)
空检查不是你唯一的问题。查看以下代码块并告诉我您的期望:
(begin
(cond [(equal? s "") no-answer]
[else (set! 8-ball-answers (append (rest 8-ball-answers)
(list next-answer)))])
next-answer)
我希望next-answer
,与条件结果无关。我想你可能希望你的else
条件在循环答案后返回next-answer
。问题是你的begin
。您测试一个条件,然后返回next-answer
。也许你想要这样的东西:
(cond [(equal? s "") no-answer]
[else (begin (set! 8-ball-answers (append (rest 8-ball-answers)
(list next-answer)))
next-answer)])
如果字符串为空,则返回no-answer
,否则返回循环next-answer
。虽然可能是正确的,但我认为这段代码相当丑陋。考虑重构循环和返回下一个答案位。结构很糟糕,因为我有它。