I would write something like this:
(define switch
((lambda (state)
(lambda ()
(begin
(set! state (not state))
state)))
#f))
Which can be invoked like this:
> (switch)
#t
> (switch)
#f
> (switch)
#t
A little explanation: the outer lambda is a function that takes an initial state and returns another function that flips that state back and forth upon each invocation. Note that the outer function is being invoked immediately with the #f
on the last line; switch is then defined as the result of this invocation, the inner function capturing state
in a closure.
You could also write something like this:
(define make-switch
(lambda ()
((lambda (state)
(lambda ()
(begin
(set! state (not state))
state)))
#f)))
make-switch
takes what we had before and wraps it in yet another function. Now what we have is a factory for making switches, each with their own internal state. So we can write something like this:
(define switch-a (make-switch))
(define switch-b (make-switch))
And see that each switch is independent of the other:
> (switch-a)
#t
> (switch-b)
#t
> (switch-b)
#f
> (switch-a)
#f
Similarly you could parameterize make-switch
to set the initial state of the switch, and on and on.
Hope this helps.