簡體   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