Next: , Previous: , Up: Derived expression types   [Index]


4.2.3 Sequencing

Both of Scheme’s sequencing constructs are named begin, but the two have slightly different forms and uses:

syntax: begin ⟨expression or definition⟩…

This form of begin can appear as part of a ⟨body⟩, or at the outermost level of a ⟨program⟩, or at the REPL, or directly nested in a begin that is itself of this form. It causes the contained expressions and definitions to be evaluated exactly as if the enclosing begin construct were not present.

Rationale: This form is commonly used in the output of macros (See Macros) which need to generate multiple definitions and splice them into the context in which they are expanded.

syntax: begin ⟨expression1⟩ ⟨expression2⟩…

This form of begin can be used as an ordinary expression. The ⟨expression⟩s are evaluated sequentially from left to right, and the values of the last ⟨expression⟩ are returned. This expression type is used to sequence side effects such as assignments or input and output.

(define x 0)

(and (= x 0)
     (begin (set! x 5)
            (+ x 1))) ⇒ 6

(begin (display "4 plus 1 equals ")
       (display (+ 4 1)))
       ⇒ unspecified
-| 4 plus 1 equals 5

Note that there is a third form of begin used as a library declaration. See Library syntax