(import (rnrs)) ;R6RS (import (rnrs base)) ;R6RS (import (scheme r5rs)) ;R7RS (import (scheme base)) ;R7RS
(begin expression or definition ...) (begin expression expression ...)
It may appear as a form in a body, library body, or top-level body, or directly nested in a begin form that appears in a body. In this case, the begin form must have the shape specified in the first synopsis line. This use of begin acts as a splicing form--the forms inside the body are spliced into the surrounding body, as if the begin wrapper were not actually present. A begin form in a body or library body must be non-empty if it appears after the first expression within the body.
It may appear as an ordinary expression and must have the shape specified in the second synopsis line. In this case, the expressions 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.
In R7RS a third form of begin appears in define-library, where it is used to begin the body of the library.
For the splicing form the rules of wherever the splice appears instead apply.
;; This example is poor style but demonstrates the ordering ;; provided by "begin". (define x 0) (begin (set! x 5) (+ x 1)) => 6 ;; If "begin" did not guarantee the evaluation order then the ;; above might have evaluated to 1. (begin (display "4 plus 1 equals ") (display (+ 4 1))) ; prints 4 plus 1 equals 5
The sequencing form is sometimes used in conditional expressions, which is a matter of personal style. Others prefer to use cond, when, or unless, which make begin unnecessary.
In R7RS define-library the begin form is often not used in favor of using include instead.
R7RS clarifies that the splicing form may appear in the REPL.