Sequential Expressions

So far, each Scheme clause shown has only had single expression, whose value is always returned immediately. There are many circumstances when a sequence of expressions need to be performed for their side effects, and the return values of most or all of them ignored. In Scheme, the body of a function is a sequential expression block, with the value of the last expression being used as the value of the function. For example, to display two values to be added, followed by their values, one couls do the following:

   (define (display-addition x y)
      (display x)
      (display " + ")
      (display y)
      (display " = ")
      (display (+ x y)))
   
Whichm when called with the arguments 3 and 4, prints "3 + 4 = 7" to the console. In cases where only one expression is expected, one can use the (begin) special form:

   (begin ((expression-1)
           (expression-2)
           (expression-3)
           ; ... 
           (final-expression)))
  

As with functions, the value of the final expression is used as the value of the whole block.

Contents Previous Next