[英]How to use counter in Scheme
I'm trying to write a program where a doctor sees only 5 patients and then the program ends.我正在尝试编写一个程序,其中医生只看 5 个病人,然后程序结束。 Right now it's not ending and it keeps asking for the next patient.现在它还没有结束,它一直在要求下一个病人。 Ignore the else in the doctor-driver-loop procedure.忽略医生驱动程序循环过程中的 else。 I add one to count in that procedure but I guess it keeps going back to zero every time.我在那个过程中加了一个来计数,但我想它每次都会回到零。 How do I fix this?我该如何解决?
(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))
Try replacing this line:尝试替换此行:
(new-patient (+ 1 count))
With these two lines:用这两行:
(set! count (+ 1 count))
(new-patient count)
In your current code, count
will always have a value of zero for each iteration of doctor-driver-loop
, because its value was never updated - the (+ 1 count)
part adds one to count
without changing count
, and the next time doctor-driver-loop
get called, count
will be zero again.在您当前的代码中,对于doctor-driver-loop
每次迭代, count
的值将始终为零,因为它的值从未更新过 - (+ 1 count)
部分在不更改count
的情况下向count
一,而下一次doctor-driver-loop
被调用, count
将再次为零。
Be aware that this is a quick fix, but not the ideal solution.请注意,这是一个快速解决方案,但不是理想的解决方案。 For starters, count
should not be defined as a global variable, instead it should be a parameter to the driver loop that gets passed with an initial value of zero and incremented when calling new-patient
with each patient that gets processed.对于初学者来说, count
不应定义为全局变量,而应该是驱动程序循环的参数,该参数以零初始值传递,并在对每个处理new-patient
调用new-patient
时递增。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.