问题描述
我正在尝试在我的计划程序中创建一个全局分数,它将在我的函数的每次迭代中增加1,减少1或保持不变。例如,当我希望分数增加1:
(set! score (+ score 1)))
我可以使用set来做到这一点!但我需要一种无需使用设置即可实现的方法!操作。任何帮助将不胜感激!
解决方法
诀窍是要意识到您可以替换以下内容:
(define (my-game ...)
(let ([score 0])
(some-kind-of-looping-construct
...
(if <not-done>
(begin
(set! score <new-score-value>)
(continue-loop))
score))))
类似这样:
(define (my-game ...)
(define (loop ... score ...)
...
(if <not-done>
(loop ... <new-score-value> ...)
score))
(loop ... 0 ...))
特别是,您可以通过对某些反复绑定变量的函数进行文本(但实际上不是)递归调用来替换任何重复分配给某个变量的循环构造。
具体来说,让我们想象一下一个看起来像
的循环结构(loop exit-fn form ...)
因此loop
是循环结构,而exit-fn
是我们退出循环所不可思议的东西。
我假设有一个函数run-game-round
,它带有一个回合数字和当前分数,运行一轮游戏并返回新分数。
因此,使用此构造,我们可以编写某种游戏循环的框架:
(let ((round 0)
(score 0))
(loop exit
(set! score (run-game-round round score))
(set! round (+ round 1))
(cond
[(> score 100)
(exit 'win)]
[(> round 100)
(exit 'lose)])))
这是非常糟糕的代码。
但是我们可以用以下代码替换此代码:
(begin
(define (run-game round score)
(cond [(> score 100)
'win]
[(> round 100)
'lose]
[else
(run-game (+ round 1)
(run-game-round round score))]))
(run-game 0 0))
这段代码确实完全相同 ,但是在任何地方都没有赋值。
,否set!
:我们可以输入list
或给定数量的args并使用递归函数。
#lang racket
(define (play-game game-round-lst)
(local [(define (make-score s)
(cond
[(equal? s 'win) 1]
[(equal? s 'drew) 0]
[(equal? s 'lose) -1]))]
(apply + (map make-score game-round-lst))))
;;; TEST
(play-game '(lose win drew lose win)) ; 0
(play-game '(win lose drew win lose win lose)) ; 0
在本地功能中使用set!
。
通过这种方法,您可以构建新游戏而不必担心每个游戏的丢失状态。
#lang racket
(define (make-game)
(local [(define score 0)
(define (setup-score n)
(set! score (+ n score)))
(define (service-manager msg)
(cond
[(equal? msg 'win)
(setup-score 1)]
[(equal? msg 'drew)
(setup-score 0)]
[(equal? msg 'lose)
(setup-score -1)]
[(equal? msg 'show-score)
score]))]
service-manager))
;;; TEST
(define game1 (make-game))
(define game2 (make-game))
(game1 'win)
(game2 'win)
(game1 'drew)
(game2 'drew)
(game1 'lose)
(game2 'lose)
(game1 'show-score) ; 0
(game2 'show-score) ; 0