(begin exp1 exp2 ...) | syntax |
returns: the result of the last expression |
The expressions exp1 exp2 … are evaluated in sequence from left to right. begin is used to sequence assignments, input/output, or other operations that cause side effects.
(define x 3) (begin (set! x (+ x 1)) (+ x x)) ⇒ 8
A begin form may contain zero or more definitions in place of the expressions exp1 exp2 …, in which case it is considered to be a definition and may appear only where definitions are valid.
(let () (begin (define x 3) (define y 4)) (+ x y)) ⇒ 7
This form of begin is primarily used by syntactic extensions that must expand into multiple definitions. (See page 91.)
The bodies of many syntactic forms, including lambda, let, let*, and letrec, as well as the result clauses of cond, case, and do, are treated as if they were inside an implicit begin; that is, the expressions making up the body or result clause are executed in sequence.
(define swap-pair! (lambda (x) (let ((temp (car x))) (set-car! x (cdr x)) (set-cdr! x temp) x))) (swap-pair! (cons 'a 'b)) ⇒ (b . a)