如何在Scheme中使用计数器

时间:2013-02-28 00:30:44

标签: scheme racket

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

(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))

1 个答案:

答案 0 :(得分:0)

尝试替换此行:

(new-patient (+ 1 count))

这两行:

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

在您当前的代码中,count 始终的每次迭代doctor-driver-loop的值都为零,因为其值永远不会更新 - (+ 1 count)部分会在count 中添加一个而不会更改count,并且下次doctor-driver-loop被调用时,count将再次为零。

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