Functions in Scheme

Functions are central in Scheme. We’ll learn about functions with a few different examples.

; Here's a function that takes two numbers and returns their sum.
(define (plus a b)
  (+ a b))

; In Scheme, we can define functions with multiple parameters easily.
(define (plus-plus a b c)
  (+ a b c))

; The main function in Scheme is typically not explicitly defined.
; Instead, we can just write our code at the top level.

; Call a function just as you'd expect, with (function-name arg1 arg2 ...).
(display "1+2 = ")
(display (plus 1 2))
(newline)

(display "1+2+3 = ")
(display (plus-plus 1 2 3))
(newline)

To run this Scheme program, save it to a file (e.g., functions.scm) and use your Scheme interpreter. For example, if you’re using Guile:

$ guile functions.scm
1+2 = 3
1+2+3 = 6

In Scheme:

  1. Functions are defined using the define keyword.
  2. Function parameters are listed in parentheses after the function name.
  3. The function body is the expression(s) following the parameter list.
  4. Scheme automatically returns the value of the last expression in a function, so explicit return statements are not needed.
  5. Function calls are written in prefix notation: (function-name arg1 arg2 ...).
  6. Scheme doesn’t have a separate main function. Instead, code at the top level is executed when the file is run.

Scheme’s functional nature allows for concise and expressive function definitions and calls. The language’s simplicity is evident in how easily we can define and use functions with varying numbers of parameters.

There are several other features to Scheme functions. One is the ability to create higher-order functions, which we’ll look at in future examples.