ZetCode

Scheme procedures

last modified November 24, 2026 Guile 3.0

A procedure is created with lambda and usually named with define. The variables and binding article showed that (define (f x) ...) is a shorthand for binding f to a lambda. This article looks at what a procedure body returns, how many arguments a procedure accepts, and how to write procedures with a variable number of arguments, optional arguments with defaults, and named keyword arguments. The examples run with GNU Guile 3.0.7.

The body and the return value

A procedure body is a sequence of expressions evaluated in order. There is no return statement: the value of the last expression is the value of the call. A procedure may also take no parameters at all.

body.scm
(define (separator)
  (display "----------")
  (newline))

(define (average a b)
  (display "averaging ")
  (display a)
  (display " and ")
  (display b)
  (newline)
  (/ (+ a b) 2))

(separator)
(display (average 3 8))
(newline)
(separator)

separator has an empty parameter list and is called as (separator). It is used only for its output. average prints a message and then computes the mean; the division is its last expression, so the exact fraction 11/2 is the returned value. The values of the earlier expressions in a body are discarded.

$ guile body.scm
----------
averaging 3 and 8
11/2
----------

Wrong number of arguments

A procedure defined with a fixed parameter list must be called with exactly that many arguments. When the compiler can see the mismatch, it warns, and the call fails at run time.

arity.scm
(define (rectangle-area width height)
  (* width height))

(display (rectangle-area 4 5))
(newline)
(display (rectangle-area 4))
(newline)

The first call is correct and prints 20. In the second one the height is missing. The compiler reports the wrong number of arguments at line 6, and when the program reaches the call, Guile stops with an error that shows the procedure and its parameters. The backtrace is left out.

$ guile arity.scm
;;; arity.scm:6:9: warning: wrong number of arguments to `rectangle-area'
20
arity.scm:1:0: In procedure rectangle-area:
Wrong number of arguments to #<procedure rectangle-area (width height)>

Rest arguments

A procedure can accept any number of extra arguments. In the parameter list, a dot before the last name makes that name a rest parameter, which receives a list of the remaining arguments. A lambda whose parameter list is a single name without parentheses receives all its arguments as a list.

rest.scm
(define (report title . items)
  (display title)
  (display " (")
  (display (length items))
  (display "): ")
  (write items)
  (newline))

(report "fruit" 'apple 'pear 'plum)
(report "tools" 'hammer)
(report "nothing")

(define collect
  (lambda args args))

(write (collect 1 2 3))
(newline)
(write (collect))
(newline)

report requires a title and collects the other arguments in items, which may be the empty list. collect is written with an explicit lambda; its parameter args is not enclosed in parentheses, so it binds the whole list of arguments, and the procedure simply returns it. The built-in list works in the same way.

$ guile rest.scm
fruit (3): (apple pear plum)
tools (1): (hammer)
nothing (0): ()
(1 2 3)
()

Optional arguments from a rest list

Standard Scheme has no syntax for optional parameters with defaults, but a rest parameter can play that role. The procedure checks whether the list is empty and uses a default value if it is.

optional.scm
(define (greet name . options)
  (let ((greeting (if (null? options) "Hello there" (car options))))
    (display greeting)
    (display ", ")
    (display name)
    (display "!")
    (newline)))

(greet "Lucia")
(greet "Peter" "Good morning")

(define (power base . options)
  (let ((exponent (if (pair? options) (car options) 2)))
    (expt base exponent)))

(display (list (power 5) (power 5 3) (power 2 10)))
(newline)

greet takes the greeting from the rest list when one is given and falls back to "Hello there" otherwise. power squares its base unless an exponent is passed. The pattern works in every implementation, but it hides the optional parameter in the body, and the procedure silently accepts extra arguments that it ignores.

$ guile optional.scm
Hello there, Lucia!
Good morning, Peter!
(25 125 1024)

case-lambda

case-lambda, from R7RS, creates a procedure with several clauses, each with its own parameter list and body. A call runs the first clause whose parameter list accepts the given number of arguments.

dispatch.scm
(define area
  (case-lambda
    ((side) (* side side))
    ((width height) (* width height))
    ((a b c)
     (let ((s (/ (+ a b c) 2)))
       (sqrt (* s (- s a) (- s b) (- s c)))))))

(display (area 4))
(newline)
(display (area 3 5))
(newline)
(display (area 3 4 5))
(newline)

(define describe
  (case-lambda
    (() "no arguments")
    ((x) "one argument")
    ((x . rest) "several arguments")))

(display (list (describe) (describe 1) (describe 1 2 3)))
(newline)

area computes the area of a square, a rectangle, or a triangle depending on the number of arguments; the triangle uses Heron's formula with the semi-perimeter s. The 3-4-5 triangle has the exact area 6 because sqrt of 36 is exact. describe shows that a clause may also use a rest parameter; it is placed last, so it catches every call with two or more arguments.

$ guile dispatch.scm
16
15
6
(no arguments one argument several arguments)

Optional arguments with define*

Guile has its own forms with optional and keyword parameters: define* and lambda*. Parameters listed after #:optional may be omitted by the caller. Each one is written either as a name or as a name with a default value in parentheses.

defaults.scm
(define* (greet name #:optional (greeting "Hello there") (mark "!"))
  (display greeting)
  (display ", ")
  (display name)
  (display mark)
  (newline))

(greet "Lucia")
(greet "Peter" "Good morning")
(greet "Anna" "Welcome back" ".")

(define* (power base #:optional (exponent 2))
  (expt base exponent))

(display (list (power 5) (power 5 3) (power 2 10)))
(newline)

greet now declares both the greeting and the closing mark as optional parameters with defaults, so it can be called with one, two, or three arguments. Unlike the rest-list version, a call with too many arguments is an error. power gets a default exponent of 2. Optional arguments are filled from left to right, so a caller cannot pass the mark without the greeting.

$ guile defaults.scm
Hello there, Lucia!
Good morning, Peter!
Welcome back, Anna.
(25 125 1024)

Keyword arguments

Parameters listed after #:key are passed by name. The caller writes a keyword, a name prefixed with #:, followed by the value. Keyword arguments can be given in any order, and each missing one takes its default.

keywords.scm
(define* (make-label text #:key (width 20) (fill #\.) (align 'left))
  (let* ((padding (max 0 (- width (string-length text))))
         (pad (make-string padding fill)))
    (if (eq? align 'right)
        (string-append pad text)
        (string-append text pad))))

(define (show label)
  (display "[")
  (display label)
  (display "]")
  (newline))

(show (make-label "Name"))
(show (make-label "Name" #:width 10))
(show (make-label "Price" #:align 'right #:fill #\space))
(show (make-label "Total" #:fill #\- #:width 12 #:align 'right))

make-label pads a text to a given width with a fill character, using make-string to build the padding. max prevents a negative length when the text is longer than the width. The calls choose any subset of the three options in any order, and the call site documents what each value means. show prints the label between brackets so the padding is visible.

$ guile keywords.scm
[Name................]
[Name......]
[               Price]
[-------Total]

Optional and keyword parameters together

A define* parameter list can contain required, optional, and keyword parameters in this order. The optional arguments are positional and are filled first; the keywords follow them.

mixed.scm
(define* (log-message text #:optional (level 'info)
                      #:key (prefix "app") (count 1))
  (display prefix)
  (display " [")
  (display level)
  (display "] ")
  (display text)
  (if (> count 1)
      (begin
        (display " (x")
        (display count)
        (display ")")))
  (newline))

(log-message "started")
(log-message "disk almost full" 'warning)
(log-message "retrying" 'warning #:count 3)
(log-message "connected" #:prefix "net")

log-message requires the text, takes an optional level, and accepts two keyword arguments. The third call passes both a level and a keyword. In the last call the keyword comes directly after the text; Guile recognises #:prefix as a keyword, so the level keeps its default info. The parameter list spans two lines only for readability.

$ guile mixed.scm
app [info] started
app [warning] disk almost full
app [warning] retrying (x3)
net [info] connected

Documentation strings

When the body of a procedure starts with a string literal and has more expressions after it, Guile stores the string as the documentation of the procedure. procedure-documentation retrieves it, and procedure-name returns the name as a symbol.

docs.scm
(define (celsius->fahrenheit c)
  "Convert a temperature from degrees Celsius to Fahrenheit."
  (+ 32 (* 9/5 c)))

(define (fahrenheit->celsius f)
  "Convert a temperature from degrees Fahrenheit to Celsius."
  (* 5/9 (- f 32)))

(display (celsius->fahrenheit 100))
(newline)
(display (fahrenheit->celsius 98.6))
(newline)
(display (procedure-documentation celsius->fahrenheit))
(newline)
(display (procedure-name fahrenheit->celsius))
(newline)

The two conversion procedures are documented with one sentence each. The string does not affect the result of a call. 98.6 degrees Fahrenheit converts to 37.0; the result is inexact because the argument is. The documentation string is printed as plain text and the name as a symbol. In the REPL, the ,describe command shows the documentation of a procedure.

$ guile docs.scm
212
37.0
Convert a temperature from degrees Celsius to Fahrenheit.
fahrenheit->celsius

Source

Lambda: basic procedure creation — GNU Guile Reference Manual

lambda* and define* — GNU Guile Reference Manual

In this article we have written procedure bodies that return the value of their last expression, seen the error for a wrong number of arguments, collected extra arguments with rest parameters, emulated optional arguments, dispatched on the number of arguments with case-lambda, used Guile's define* with optional and keyword parameters, and documented procedures with strings. The recursion article continues with procedures that call themselves.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Scheme tutorials.