繁体   English   中英

如何在Scheme中使用计数器

[英]How to use counter in Scheme

我正在尝试编写一个程序,其中医生只看 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))

尝试替换此行:

(new-patient (+ 1 count))

用这两行:

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM