The Scheme system lets you type one expression, then it evaluates it,
prints the result, and prompts you for another expression. What if
you want to type two or three expressions and have them executed
sequentially, i.e., in the written order? You can use a
expression, which just sequences its subexpressions, and returns the
value of the last subexpression in the sequence.
First let's define a flag variable, which we'll use to hold a boolean value.
Scheme> (define flag #f) #void
Now a sequence to "toggle" (reverse) the value of the flag and return the
new value. If the flag holds
#f, we set it to
#t, and vice
Scheme> (begin (if flag (set! flag #f) (set! flag #t)) flag) #t
This evaluated the
if expression, which toggled the flag, and then
flag, which fetched the value of the variable
flag, and returned that value.
We can also write a procedure to do this, so that we don't have to
write this expression out next time we want to do it. We won't
begin here, because the body of a procedure is
automatically treated like a
begin---the expressions are
evaluated in order, and the value of the last one is returned as
the return value of the procedure.
Scheme> (define (toggle-flag) (if flag (set! flag #f) (set! flag #t)) flag) #void
Now try using it.
Scheme>flag #t Scheme>(toggle-flag) #f Scheme>flag #f Scheme>(toggle-flag) #t