Skip to content
Tutorials Center
My learning

Topics

Lesson 28 of 38 ยท Modules and Contracts

Contracts Basics

Learn Racket contracts: -> and contract-out, predicates and combinators like or/c and listof, blame at module boundaries, and a JavaScript contract-wrapper stand-in.

Racket is dynamically typed, which means a function called with the wrong kind of argument fails somewhere inside it, often with a confusing message. A contract states, at the boundary of a module, what a function expects and what it promises. If someone breaks the agreement, Racket stops immediately and blames the party that broke it. Contracts are Racket's answer to documentation that is always checked.

This lesson introduces contract-out, the arrow contract ->, common combinators, and the idea of blame. It builds on Modules and provide.

Racket's contract system is not available on our site, so the Racket code is read-only, and I print results only where the behavior is certain. The runnable JavaScript is a stand-in that wraps functions with checks and blame messages in the same spirit.

Your first contract

Replace provide with contract-out and attach a contract to each name:

RACKET
#lang racket

(provide (contract-out
          [average (-> (listof real?) real?)]
          [clamp   (-> real? real? real? real?)]))

(define (average nums)
  (/ (apply + nums) (length nums)))

(define (clamp x lo hi)
  (max lo (min x hi)))

(-> (listof real?) real?) reads "a function taking a list of real numbers and returning a real number". The part before the last item lists argument contracts; the last item is the result contract. If a caller writes (average "oops") from another module, Racket raises an error that blames the caller and states which contract was violated. If average itself returned a string, the error would blame the module that defines average.

Calls inside the defining module are not checked: a module trusts itself. The boundary is where contracts live, which makes them cheap compared with checking every internal call.

Building contracts from parts

Any one-argument predicate is a contract. Racket provides many combinators:

RACKET
(or/c string? #f)               ; a string or #f
(and/c integer? positive?)      ; a positive integer
(listof string?)                ; a list of strings
(hash/c symbol? number?)        ; hash from symbols to numbers
(one-of/c 'red 'green 'blue)    ; one of these symbols
(between/c 1 10)                ; real between 1 and 10 (inclusive)
(cons/c number? string?)        ; a pair
(vectorof integer?)             ; vector

You can also write a dependent contract, where the result depends on the arguments:

RACKET
(provide (contract-out
          [substring-of
           (->i ([s string?] [n (s) (and/c natural? (<=/c (string-length s)))])
                [result string?])]))

Here n must be a natural number no larger than the length of s. Optional and keyword arguments have their own forms (->* and keyword arrows), but the basic -> covers most functions.

Blame: who broke the deal?

When a contract fails, the error names two parties: the positive party (the module that provided the value) and the negative party (the module that is using it). For a function contract:

  • Bad argument from the caller: the caller is blamed.
  • Bad result from the function: the function's module is blamed.

This is the core idea of contract research: finding the real culprit, not just where the crash showed up.

sequenceDiagram
  participant C as caller module
  participant K as contract wrapper
  participant F as average
  C->>K: (average "oops")
  K-->>C: argument fails (listof real?): blame caller
  C->>K: (average (list 1 2 3))
  K->>F: checked args
  F-->>K: 2
  K-->>C: result checked (real?), passed through

The wrapper checks arguments before calling and the result before returning.

Stand-in: contract wrappers with blame

This JavaScript block builds the same idea with higher-order functions: arrow(argChecks, resultCheck) wraps a function, and failures say who is to blame.

JS Stand-in: function contracts with blame

Press Run (or Ctrl + Enter) to see the console output here.

No output.

You see the two failure modes: bad input blames the caller, bad output blames the provider.

Performance and where to use contracts

Checking costs time. That is why Racket puts contracts at module boundaries and not on every call, and why some checks, like (listof real?) on a long list, can be expensive. For performance-critical code, keep contracts simple (real? instead of a deep structure check), or place them only on the public API. Contracts are most valuable on libraries and on code that several people maintain.

A mixed strategy works well: contract the exported API, use plain define for internals, and write tests (rackunit) for behavior that contracts cannot state.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does (-> real? real? string?) describe?

    All items but the last are argument contracts; the last is the result contract.
  2. 2. If a caller passes a string to a function that promises (listof real?), who is blamed?

    A bad argument violates the caller's side of the agreement.
  3. 3. Where does contract-out check values?

    Contracts wrap exported bindings, so internal calls are not checked.
  4. 4. Which contract means "a string or #f"?

    or/c accepts a value satisfying any of its contracts; #f is also a valid contract meaning exactly #f.

Summary

  • contract-out attaches contracts to exports; -> describes function argument and result contracts.
  • Any predicate is a contract; or/c, and/c, listof, hash/c, between/c and others build bigger ones.
  • Failures name the guilty party: caller for bad arguments, provider for bad results.
  • Contracts live at module boundaries, which keeps their cost contained.

Next: Structs and Contracts