Functions

The first advantage to creating your own functions (also called “procedures” in Scheme) is to make modular code, with subcomponents that can be reused. Scheme uses procedures in a much more fundamental way, however, as it belongs to the family of functional programming languages, a term that will become clearer later in this tutorial. The most frequently used syntax to define a function looks much like how define was used to define simple variables, except that the first element in define has parentheses, which give the function name and signature.

(define (function-name argument1 argument2 ...)
  function body ...)

The function’s body is a sequence of expressions. Just like in a begin expression, they are evaluated in order and the value of the last one is returned. Here is a first example:

(define c 299792458)

(define (E m)
  (* m c c))

After this function has been defined, it can be called:

(E 56.6)
 5.08695431165039e18

Since the return value of the function is the value of the last expression, the values that the other expressions before the last one evaluate to are simply ignored. These expressions can only be useful for their side effects, namely what actions they perform apart from returning a value. A commonly seen application is to print debugging messages.

(define (double x)
  (display "double called with the parameter ")
  (display x)
  (display "\n")
  (* 2 x))

(double 5)
 double called with the parameter 5
 10