0

我正在尝试编写一个程序,其中医生只看到 5 名患者,然后程序结束。现在它还没有结束,它一直在寻找下一个病人。忽略医生驱动循环过程中的 else。我在该过程中添加了一个计数,但我想它每次都会回到零。我该如何解决?

(define count 0)

(define (new-patient counter)
  (if (= counter 5) (write-line 'doctor has seen 5 patients today so the day is now over)
    (visit-doctor (ask-patient-name))))

(define (doctor-driver-loop name earlier-responses)
  (newline)
 (write '**)
  (let ((user-response (read)))
   (cond ((equal? user-response '(goodbye))
         (write-line (list 'goodbye name))
         (write-line '(see you next week))
         (new-patient (+ 1 count)))
      (else (write-line (reply (responses-list earlier-responses user-response) user-response))
            (doctor-driver-loop name (responses-list earlier-responses user-response))))))

(define (visit-doctor name)
  (write-line (list 'hello name))
  (write-line '(what seems to be the trouble?))
  (doctor-driver-loop name initial-earlier-response))
4

1 回答 1

1

尝试替换此行:

(new-patient (+ 1 count))

用这两行:

(set! count (+ 1 count))
(new-patient count)

在您当前的代码中,对于 的每次迭代count始终具有零值doctor-driver-loop,因为它的值从未更新 - 该(+ 1 count)部分在count 更改的情况下加一count,并且下一次doctor-driver-loop被调用时,count将再次为零。

请注意,这是一个快速修复,但不是理想的解决方案。对于初学者,count不应将其定义为全局变量,而应将其作为驱动程序循环的参数,该参数以初始值 0 传递,并在new-patient与每个被处理的患者一起调用时递增。

于 2013-02-28T01:09:26.017 回答