Like a contract between two business partners, a software contract is an agreement between two parties. The agreement specifies obligations and guarantees for each “product” (or value) that is handed from one party to the other.
A contract thus establishes a boundary between the two parties. Whenever a value crosses this boundary, the contract monitoring system performs contract checks, making sure the partners abide by the established contract.
promises to all clients of the above module that the value of amount will always be a positive number. The contract system monitors the module’s obligation carefully. Every time a client refers to amount, the monitor checks that the value of amount is indeed a positive number.
The contracts library is built into the Racket language, but if you wish to use racket/base, you can explicitly require the contracts library like this:
|(require racket/contract) ; now we can write contracts|
|(define amount ...)|
If we bind amount to a number that is not positive,
|(define amount 0)|
then, when the module is required, the monitoring system signals a violation of the contract and blames the module for breaking its promises.
An even bigger mistake would be to bind amount to a non-number value:
|(define amount 'amount)|
In this case, the monitoring system will apply positive? to a symbol, but positive? reports an error, because its domain is only numbers. To make the contract capture our intentions for all Racket values, we can ensure that the value is both a number and is positive, combining the two contracts with and/c:
|[amount (and/c number? positive?)])|
All of the contracts and module in this chapter (excluding those just following) are written using the standard #lang syntax for describing modules. Since modules serve as the boundary between parties in a contract, examples involve multiple modules.
To experiment with multiple modules within a single module or within DrRacket’s definitions area, use the racket/load language. The contents of such a module can be other modules (and require statements), using the longhand parenthesized syntax for a module (see The module Form). For example, try the example earlier in this section as follows:
|(module m racket|
|(provide/contract [amount (and/c number? positive?)])|
|(define amount 150))|
|(module n racket|
|(+ amount 10))|
Each of the modules and their contracts are wrapped in parentheses with the module keyword at the front. The first form after module is the name of the module to be used in a subsequent require statement (where each reference through a require prefixes the name with a quote). The second form after module is the language, and the remaining forms are the body of the module. After all of the modules, a require starts one of the modules plus anything that is requires.