The -> contract constructor works for functions that take a fixed number of arguments and where the result contract is independent of the input arguments. To support other kinds of functions, Racket supplies additional contract constructors, notably ->* and ->i .
Take a look at this excerpt from a string-processing module:
;pad the given str left and right with;the (optional) char so that it is centeredstr
The module exports string-pad-center, a function that creates a string of a given width with the given string in the center. The default fill character is #\space; if the client module wishes to use a different character, it may call string-pad-center with a third argument, a char, overwriting the default.
The function definition uses optional arguments, which is appropriate for this kind of functionality. The interesting point here is the formulation of the contract for the string-pad-center.
The contract combinator ->* , demands several groups of contracts:
The first one is a parenthesized group of contracts for all required arguments. In this example, we see two: string? and natural-number/c .
The second one is a parenthesized group of contracts for all optional arguments: char? .
The last one is a single contract: the result of the function.
Note that if a default value does not satisfy a contract, you won’t get a contract error for this interface. If you can’t trust yourself to get the initial value right, you need to communicate the initial value across a boundary.
The max operator consumes at least one real number, but it accepts any number of additional arguments. You can write other such functions using a rest argument, such as in max-abs:
See Declaring a Rest Argument for an introduction to rest arguments.
To describe this function through a contract, you can use the ... feature of -> .
Alternatively, you can use ->* with a #:rest keyword, which specifies a contract on a list of arguments after the required and optional arguments:
As always for ->* , the contracts for the required arguments are enclosed in the first pair of parentheses, which in this case is a single real number. The empty pair of parenthesis indicates that there are no optional arguments (not counting the rest arguments). The contract for the rest argument follows #:rest; since all additional arguments must be real numbers, the list of rest arguments must satisfy the contract (listof real? ).
It turns out that the -> contract constructor also contains support for keyword arguments. For example, consider this function, which creates a simple GUI and asks the user a yes-or-no question:
See Declaring Keyword Arguments for an introduction to keyword arguments.
#:defaultanswer#:titletitle#:widthw#:heighth)[label"Yes"][parentd][label"No"][parentd]answer)[ask-yes-or-no-question#:defaultboolean?#:titlestring?#:widthexact-integer?#:heightexact-integer?
If you really want to ask a yes-or-no question via a GUI, you should use message-box/custom . For that matter, it’s usually better to provide buttons with more specific answers than “yes” and “no.”
The contract for ask-yes-or-no-question uses -> , and in the same way that lambda (or define -based functions) allows a keyword to precede a functions formal argument, -> allows a keyword to precede a function contract’s argument contract. In this case, the contract says that ask-yes-or-no-question must receive four keyword arguments, one for each of the keywords #:default, #:title, #:width, and #:height. As in a function definition, the order of the keywords in -> relative to each other does not matter for clients of the function; only the relative order of argument contracts without keywords matters.
Of course, many of the parameters in ask-yes-or-no-question (from the previous question) have reasonable defaults and should be made optional:
#:defaultanswer#:title[title"Yes or No?"]#:width[w400]#:height[h200])... )
To specify this function’s contract, we need to use ->* again. It supports keywords just as you might expect in both the optional and mandatory argument sections. In this case, we have the mandatory keyword #:default and optional keywords #:title, #:width, and #:height. So, we write the contract like this:
[ask-yes-or-no-question#:widthexact-integer?
That is, we put the mandatory keywords in the first section, and we put the optional ones in the second section.
A function defined with case-lambda might impose different constraints on its arguments depending on how many are provided. For example, a report-cost function might convert either a pair of numbers or a string into a new string:
See Arity-Sensitive Functions: case-lambda for an introduction to case-lambda .
> (report-cost58)"between 5γγ« and 8γγ«"
> (report-cost"millions")"millions of dollars"
[report-cost
The following is an excerpt from an imaginary numerics module:
The word “indy” is meant to suggest that blame may be assigned to the contract itself, because the contract must be considered an independent component. The name was chosen in response to two existing labels—“lax” and “picky”—for different semantics of function contracts in the research literature.
In general, a dependent function contract looks just like the more general ->* contract, but with names added that can be used elsewhere in the contract.
Going back to the bank-account example, suppose that we generalize the module to support multiple accounts and that we also include a withdrawal operation. The improved bank-account module includes an account structure type and the following functions:
Besides requiring that a client provide a valid amount for a withdrawal, however, the amount should be less than or equal to the specified account’s balance, and the resulting account will have less money than it started with. Similarly, the module might promise that a deposit produces an account with money added to the account. The following implementation enforces those constraints and guarantees through contracts:
;section 1: the contract definitions;section 2: the exports[result(accamt)[amtamount/c])[result(accamt);section 3: the function definitions
The contracts in section 2 provide typical type-like guarantees for create and balance. For withdraw and deposit, however, the contracts check and guarantee the more complicated constraints on balance and deposit. The contract on the second argument to withdraw uses (balanceacc) to check whether the supplied withdrawal amount is small enough, where acc is the name given within ->i to the function’s first argument. The contract on the result of withdraw uses both acc and amt to guarantee that no more than that requested amount was withdrawn. The contract on deposit similarly uses acc and amount in the result contract to guarantee that at least as much money as provided was deposited into the account.
As written above, when a contract check fails, the error message is not great. The following revision uses flat-named-contract within a helper function mk-account-contract to provide better error messages.
;section 1: the contract definitions;section 2: the exports[amtamount/c])[result(accamt);section 3: the function definitions
The range contract ensures that the function only modifies the children of parent by adding a new child to the front of the list. It accomplishes this by using the _ instead of a normal identifier, which tells the contract library that the range contract does not depend on the values of any of the results, and thus the contract library evaluates the expression following the _ when the function is called, instead of when it returns. Therefore the call to the get-children method happens before the function under the contract is called. When the function under contract returns, its result is passed in as child, and the contract ensures that the children after the function return are the same as the children before the function called, but with one more child, at the front of the list.
(cond(splitl'()))
Imagine yourself writing a contract for a function that accepts some other function and a list of numbers that eventually applies the former to the latter. Unless the arity of the given function matches the length of the given list, your procedure is in trouble.
;(number ... -> (union #f number?)) (listof number) -> void
The argument of n-step is proc, a function proc whose results are either numbers or false, and a list. It then applies proc to the list inits. As long as proc returns a number, n-step treats that number as an increment for each of the numbers in inits and recurs. When proc returns false , the loop stops.
;nat -> nat(n-stepf'(2));nat nat -> nat(n-stepg'(11))
[n-stepf()