I am trying to create a global score in my scheme program and it will either increase by 1, decrease by 1 or not change for each iteration of my function. For example, I have this in my function when I want the score to increase by 1:
(set! score (+ score 1)))
I am able to do this using set! but I need a way to achieve it without using the set! operation. Any help would be appreciated!
The trick is to realise that you can replace something like this:
With something like this:
In particular you can replace any kind of looping construct which repeatedly assigns to some variable by textually (but not actually) recursive calls to some function which repeatedly binds a variable.
To be concrete about this let's imagine we have a looping construct which looks like
So
loop
is the loop construct, andexit-fn
is the magic thing we call to exit the loop.And I'll assume there is some function
run-game-round
which takes a round number and the current score, runs a round of the game and returns the new score.So using this construct we can write the skeleton of some kind of game loop:
And this is fairly horrible code.
But we can replace this code with this:
And this code does exactly the same thing but there is no assignment anywhere.