text
stringlengths
12
127k
# 4.7 Conditionals The last test-expr in a [cond](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=if.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fletstx-scheme..rkt%2529._cond%2529%2529&version=8.18.0.13) can be replaced by [else](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=if.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fletstx-scheme..rkt%2529._else%2529%2529&version=8.18.0.13). In terms of evaluation, [else](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=if.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fletstx-scheme..rkt%2529._else%2529%2529&version=8.18.0.13) serves as a synonym for #t, but it clarifies that the last clause is meant to catch all remaining cases. If [else](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=if.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fletstx-scheme..rkt%2529._else%2529%2529&version=8.18.0.13) is not used, then it is possible that no test-exprs produce a true value; in that case, the result of the [cond](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=if.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fletstx-scheme..rkt%2529._cond%2529%2529&version=8.18.0.13) expression is [#<void>](void_undefined.html). Examples:
# 4.7 Conditionals > ```racket > > ( cond [ ( = 2 3 ) ( error "wrong!" ) ] [ ( = 2 2 ) ' ok ] ) > 'ok > > ( cond [ ( = 2 3 ) ( error "wrong!" ) ] ) > > ( cond [ ( = 2 3 ) ( error "wrong!" ) ] [ else ' ok ] ) > 'ok > ``` > ``` (define (got-milk? lst) > ( cond > [ ( null? lst ) #f ] > [ ( eq? ' milk ( car lst ) ) #t ] > [ else ( got-milk? ( cdr lst ) ) ] ) ) > ( got-milk? ' ( apple banana ) ) > #f > > ( got-milk? ' ( apple milk banana ) ) > #t ``` (make-running-total) →``` #### 4.9.1 Guidelines for Using Assignment Although using [set!](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=set_.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._set%2521%2529%2529&version=8.18.0.13) is sometimes appropriate, Racket style generally discourages the use of [set!](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=set_.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._set%2521%2529%2529&version=8.18.0.13). The following guidelines may help explain when using [set!](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=set_.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._set%2521%2529%2529&version=8.18.0.13) is appropriate. - As in any modern language, assigning to a shared identifier is no substitute for passing an argument to a procedure or getting its result. Really awful example: > <table data-cellpadding="0" data-cellspacing="0"><colgroup><col style="width: 100%" /></colgroup><tbody><tr><td><pre><code>( define name &quot;unknown&quot; ) > ( define result &quot;unknown&quot; ) > ( define ( greet ) > ( set! result ( string-append &quot;Hello, &quot; name ) ) )</code></pre></td></tr><tr><td><p> </p></td></tr><tr><td><pre><code>&gt; ( set! name &quot;John&quot; ) > &gt; ( greet ) > &gt; result > &quot;Hello, John&quot;</code></pre></td></tr></tbody></table> Ok example: > <table data-cellpadding="0" data-cellspacing="0"><colgroup><col style="width: 100%" /></colgroup><tbody><tr><td><pre><code>( define ( greet name ) > ( string-append &quot;Hello, &quot; name ) )</code></pre></td></tr><tr><td><p> </p></td></tr><tr><td><pre><code>&gt; ( greet &quot;John&quot; ) > &quot;Hello, John&quot; > &gt; ( greet &quot;Anna&quot; ) > &quot;Hello, Anna&quot;</code></pre></td></tr></tbody></table> - A sequence of assignments to a local variable is far inferior to nested bindings. Bad example: > ```racket > > ( let ( [ tree 0 ] ) ( set! tree ( list tree 1 tree ) ) ( set! tree ( list tree 2 tree ) ) ( set! tree ( list tree 3 tree ) ) tree ) > '(((0 1 0) 2 (0 1 0)) 3 ((0 1 0) 2 (0 1 0))) > ``` Ok example: > ```racket > > ( let* ( [ tree 0 ] [ tree ( list tree 1 tree ) ] [ tree ( list tree 2 tree ) ] [ tree ( list tree 3 tree ) ] ) tree ) > '(((0 1 0) 2 (0 1 0)) 3 ((0 1 0) 2 (0 1 0))) > ``` - Using assignment to accumulate results from an iteration is bad style. Accumulating through a loop argument is better. Somewhat bad example: > ``` (define (sum lst) > ( let ( [ s 0 ] ) > ( for-each ( lambda ( i ) ( set! s ( + i s ) ) ) > lst ) > s ) )   > ( sum ' ( 1 2 3 ) ) > 6 ```
# 4.7 Conditionals Ok example: > ``` (define (sum lst) > ( let loop ( [ lst lst ] [ s 0 ] ) > ( if ( null? lst ) > s > ( loop ( cdr lst ) ( + s ( car lst ) ) ) ) ) ) > ( sum ' ( 1 2 3 ) ) > 6``` Better (use an existing function) example: > <table data-cellpadding="0" data-cellspacing="0"><colgroup><col style="width: 100%" /></colgroup><tbody><tr><td><pre><code>( define ( sum lst ) > ( apply + lst ) )</code></pre></td></tr><tr><td><p> </p></td></tr><tr><td><pre><code>&gt; ( sum &#39; ( 1 2 3 ) ) > 6</code></pre></td></tr></tbody></table> Good (a general approach) example: > ``` (define (sum lst) > ( for/fold ( [ s 0 ] ) > ( [ i ( in-list lst ) ] ) > ( + s i ) ) ) > ( sum ' ( 1 2 3 ) ) > 6
# 4.7 Conditionals ``` - For cases where stateful objects are necessary or appropriate, then implementing the object’s state with set! is fine. Ok example: > ``` (define next-number! > ( let ( [ n 0 ] ) > ( lambda ( ) > ( set! n ( add1 n ) ) > n ) ) )   > ( next-number! ) > 1 > > ( next-number! ) > 2 > > ( next-number! ) > 3``` All else being equal, a program that uses no assignments or mutation is always preferable to one that uses assignments or mutation. While side effects are to be avoided, however, they should be used if the resulting code is significantly more readable or if it implements a significantly better algorithm. The use of mutable values, such as vectors and hash tables, raises fewer suspicions about the style of a program than using [set!](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=set_.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._set%2521%2529%2529&version=8.18.0.13) directly. Nevertheless, simply replacing [set!](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=set_.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._set%2521%2529%2529&version=8.18.0.13)s in a program with [vector-set!](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=vectors.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._vector-set%2521%2529%2529&version=8.18.0.13)s obviously does not improve the style of the program. #### 4.9.2 Multiple Values: [set!-values](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=set_.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fmore-scheme..rkt%2529._set%2521-values%2529%2529&version=8.18.0.13) > > > <img src="magnify.png" width="24" height="24" alt="+" />[Assignment: set! and set!-values](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=set_.html&version=8.18.0.13) in [The Racket Reference](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=index.html&version=8.18.0.13) also documents [set!-values](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=set_.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fmore-scheme..rkt%2529._set%2521-values%2529%2529&version=8.18.0.13). The [set!-values](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=set_.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fmore-scheme..rkt%2529._set%2521-values%2529%2529&version=8.18.0.13) form assigns to multiple variables at once, given an expression that produces an appropriate number of values: > > | | > > |---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| > > | ([set!-values](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=set_.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fmore-scheme..rkt%2529._set%2521-values%2529%2529&version=8.18.0.13) (id ...) expr) | This form is equivalent to using [let-values](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=let.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._let-values%2529%2529&version=8.18.0.13) to receive multiple results from expr, and then assigning the results individually to the ids using [set!](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=set_.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._set%2521%2529%2529&version=8.18.0.13). Examples: > ```racket > ( define game ( let ( [ w 0 ] [ l 0 ] ) ( lambda ( win? ) ( if win? ( set! w ( + w 1 ) ) ( set! l ( + l 1 ) ) ) ( begin0 ( values w l ) ; swap sides... ( set!-values ( w l ) ( values l w ) ) ) ) ) ) > > ( game #t ) > 1 0 > > ( game #t ) > 1 1 > > ( game #f ) > 1 2 > ``` ------------------------------------------------------------------------ # 4.10 Quoting: quote and ' ### 4.10 Quoting: [quote](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=quote.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._quote%2529%2529&version=8.18.0.13) and ’ > > > <img src="magnify.png" width="24" height="24" alt="+" />[Literals: quote and #%datum](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=quote.html&version=8.18.0.13) in [The Racket Reference](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=index.html&version=8.18.0.13) also documents [quote](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=quote.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._quote%2529%2529&version=8.18.0.13). The [quote](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=quote.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._quote%2529%2529&version=8.18.0.13) form produces a constant: > > | | > > |---------------| > > | (quote datum) | The syntax of a datum is technically specified as anything that the [read](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Reading.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._read%2529%2529&version=8.18.0.13) function parses as a single element. The value of the [quote](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=quote.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._quote%2529%2529&version=8.18.0.13) form is the same value that [read](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Reading.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._read%2529%2529&version=8.18.0.13) would produce given datum. The datum can be a symbol, a boolean, a number, a (character or byte) string, a character, a keyword, an empty list, a pair (or list) containing more such values, a vector containing more such values, a hash table containing more such values, or a box containing another such value. Examples: > ```racket > > ( quote apple ) > 'apple > > ( quote #t ) > #t > > ( quote 42 ) > 42 > > ( quote "hello" ) > "hello" > > ( quote ( ) ) > '() > > ( quote ( ( 1 2 3 ) # ( "z" x ) . the-end ) ) > '((1 2 3) #("z" x) . the-end) > > ( quote ( 1 2 . ( 3 ) ) ) > '(1 2 3) > ``` As the last example above shows, the datum does not have to match the normalized printed form of a value. A datum cannot be a printed representation that starts with #\<, so it cannot be [#<void>](void_undefined.html), [#<undefined>](void_undefined.html), or a procedure. The [quote](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=quote.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._quote%2529%2529&version=8.18.0.13) form is rarely used for a datum that is a boolean, number, or string by itself, since the printed forms of those values can already be used as constants. The [quote](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=quote.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._quote%2529%2529&version=8.18.0.13) form is more typically used for symbols and lists, which have other meanings (identifiers, function calls, etc.) when not quoted. An expression > > | | > > |--------| > > | 'datum | is a shorthand for > (quote datum) and this shorthand is almost always used instead of [quote](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=quote.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._quote%2529%2529&version=8.18.0.13). The shorthand applies even within the datum, so it can produce a list containing [quote](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=quote.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._quote%2529%2529&version=8.18.0.13). > > > <img src="magnify.png" width="24" height="24" alt="+" />[Reading Quotes](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=reader.html%23%2528part._parse-quote%2529&version=8.18.0.13) in [The Racket Reference](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=index.html&version=8.18.0.13) provides more on the ' shorthand. Examples: > ```racket > > ' apple > 'apple > > ' "hello" > "hello" > > ' ( 1 2 3 ) > '(1 2 3) > > ( display ' ( you can ' me ) ) > (you can (quote me)) > ``` ------------------------------------------------------------------------ # 4.11 Quasiquoting: quasiquote and lsquo ### 4.11 Quasiquoting: [quasiquote](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=quasiquote.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fletstx-scheme..rkt%2529._quasiquote%2529%2529&version=8.18.0.13) and ‘ > > > <img src="magnify.png" width="24" height="24" alt="+" />[Quasiquoting: quasiquote, unquote, and unquote-splicing](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=quasiquote.html&version=8.18.0.13) in [The Racket Reference](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=index.html&version=8.18.0.13) also documents [quasiquote](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=quasiquote.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fletstx-scheme..rkt%2529._quasiquote%2529%2529&version=8.18.0.13). The [quasiquote](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=quasiquote.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fletstx-scheme..rkt%2529._quasiquote%2529%2529&version=8.18.0.13) form is similar to [quote](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=quote.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._quote%2529%2529&version=8.18.0.13): > > | | > > |---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| > > | ([quasiquote](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=quasiquote.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fletstx-scheme..rkt%2529._quasiquote%2529%2529&version=8.18.0.13) datum) | However, for each ([unquote](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=quasiquote.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._unquote%2529%2529&version=8.18.0.13) expr) that appears within the datum, the expr is evaluated to produce a value that takes the place of the [unquote](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=quasiquote.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._unquote%2529%2529&version=8.18.0.13) sub-form. Example: > ```racket > > ( quasiquote ( 1 2 ( unquote ( + 1 2 ) ) ( unquote ( - 5 1 ) ) ) ) > '(1 2 3 4) > ``` This form can be used to write functions that build lists according to certain patterns. Examples: > ```racket > > ( define ( deep n ) ( cond [ ( zero? n ) 0 ] [ else ( quasiquote ( ( unquote n ) ( unquote ( deep ( - n 1 ) ) ) ) ) ] ) ) > > ( deep 8 ) > '(8 (7 (6 (5 (4 (3 (2 (1 0)))))))) > ``` Or even to cheaply construct expressions programmatically. (Of course, 9 times out of 10, you should be using a [macro](macros.html) to do this (the 10th time being when you’re working through a textbook like [PLAI](https://www.cs.brown.edu/~sk/Publications/Books/ProgLangs/)).) Examples: > ```racket > > ( define ( build-exp n ) ( add-lets n ( make-sum n ) ) ) > > ( define ( add-lets n body ) ( cond [ ( zero? n ) body ] [ else ( quasiquote ( let ( [ ( unquote ( n->var n ) ) ( unquote n ) ] ) ( unquote ( add-lets ( - n 1 ) body ) ) ) ) ] ) ) > > ( define ( make-sum n ) ( cond [ ( = n 1 ) ( n->var 1 ) ] [ else ( quasiquote ( + ( unquote ( n->var n ) ) ( unquote ( make-sum ( - n 1 ) ) ) ) ) ] ) ) > > ( define ( n->var n ) ( string->symbol ( format "x~a" n ) ) ) > > ( build-exp 3 ) > '(let ((x3 3)) (let ((x2 2)) (let ((x1 1)) (+ x3 (+ x2 x1))))) > ``` The [unquote-splicing](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=quasiquote.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._unquote-splicing%2529%2529&version=8.18.0.13) form is similar to [unquote](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=quasiquote.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._unquote%2529%2529&version=8.18.0.13), but its expr must produce a list, and the [unquote-splicing](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=quasiquote.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._unquote-splicing%2529%2529&version=8.18.0.13) form must appear in a context that produces either a list or a vector. As the name suggests, the resulting list is spliced into the context of its use. Example: > ```racket > > ( quasiquote ( 1 2 ( unquote-splicing ( list ( + 1 2 ) ( - 5 1 ) ) ) 5 ) ) > '(1 2 3 4 5) > ``` Using splicing we can revise the construction of our example expressions above to have just a single [let](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=let.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fletstx-scheme..rkt%2529._let%2529%2529&version=8.18.0.13) expression and a single [+](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=generic-numbers.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._%252B%2529%2529&version=8.18.0.13) expression. Examples: > ```racket > > ( define ( build-exp n ) ( add-lets n ( quasiquote ( + ( unquote-splicing ( build-list n ( λ ( x ) ( n->var ( + x 1 ) ) ) ) ) ) ) ) ) > > ( define ( add-lets n body ) ( quasiquote ( let ( unquote ( build-list n ( λ ( n ) ( quasiquote [ ( unquote ( n->var ( + n 1 ) ) ) ( unquote ( + n 1 ) ) ] ) ) ) ) ( unquote body ) ) ) ) > > ( define ( n->var n ) ( string->symbol ( format "x~a" n ) ) ) > > ( build-exp 3 ) > '(let ((x1 1) (x2 2) (x3 3)) (+ x1 x2 x3)) > ``` If a [quasiquote](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=quasiquote.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fletstx-scheme..rkt%2529._quasiquote%2529%2529&version=8.18.0.13) form appears within an enclosing [quasiquote](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=quasiquote.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fletstx-scheme..rkt%2529._quasiquote%2529%2529&version=8.18.0.13) form, then the inner [quasiquote](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=quasiquote.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fletstx-scheme..rkt%2529._quasiquote%2529%2529&version=8.18.0.13) effectively cancels one layer of [unquote](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=quasiquote.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._unquote%2529%2529&version=8.18.0.13) and [unquote-splicing](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=quasiquote.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._unquote-splicing%2529%2529&version=8.18.0.13) forms, so that a second [unquote](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=quasiquote.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._unquote%2529%2529&version=8.18.0.13) or [unquote-splicing](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=quasiquote.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._unquote-splicing%2529%2529&version=8.18.0.13) is needed. Examples: > ```racket > > ( quasiquote ( 1 2 ( quasiquote ( unquote ( + 1 2 ) ) ) ) ) > '(1 2 (quasiquote (unquote (+ 1 2)))) > > ( quasiquote ( 1 2 ( quasiquote ( unquote ( unquote ( + 1 2 ) ) ) ) ) ) > '(1 2 (quasiquote (unquote 3))) > > ( quasiquote ( 1 2 ( quasiquote ( ( unquote ( + 1 2 ) ) ( unquote ( unquote ( - 5 1 ) ) ) ) ) ) ) > '(1 2 (quasiquote ((unquote (+ 1 2)) (unquote 4)))) > ``` The evaluations above will not actually print as shown. Instead, the shorthand form of [quasiquote](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=quasiquote.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fletstx-scheme..rkt%2529._quasiquote%2529%2529&version=8.18.0.13) and [unquote](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=quasiquote.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._unquote%2529%2529&version=8.18.0.13) will be used: \` (i.e., a backquote) and , (i.e., a comma). The same shorthands can be used in expressions: Example: > ```racket > > ` ( 1 2 ` ( , ( + 1 2 ) , , ( - 5 1 ) ) ) > '(1 2 `(,(+ 1 2) ,4)) > ``` The shorthand form of [unquote-splicing](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=quasiquote.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._unquote-splicing%2529%2529&version=8.18.0.13) is ,@: Example: > ```racket > > ` ( 1 2 ,@ ( list ( + 1 2 ) ( - 5 1 ) ) ) > '(1 2 3 4) > ``` ------------------------------------------------------------------------ # 4.12 Simple Dispatch: case ### 4.12 Simple Dispatch: [case](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=case.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fmore-scheme..rkt%2529._case%2529%2529&version=8.18.0.13) The [case](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=case.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fmore-scheme..rkt%2529._case%2529%2529&version=8.18.0.13) form dispatches to a clause by matching the result of an expression to the values for the clause: > > ``` (case expr > > [ ( datum ...+ ) body ...+ ] > > ... ) ```
# 4.7 Conditionals (parameter) →``` > > > The term “parameter” is sometimes used to refer to the arguments of a function, but “parameter” in Racket has the more specific meaning described here. For example, the [error-print-width](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=exns.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._error-print-width%2529%2529&version=8.18.0.13) parameter controls how many characters of a value are printed in an error message: > ```racket > > ( parameterize ( [ error-print-width 5 ] ) ( car ( expt 10 1024 ) ) ) > car: contract violation > expected: pair? > given: 10... > > ( parameterize ( [ error-print-width 10 ] ) ( car ( expt 10 1024 ) ) ) > car: contract violation > expected: pair? > given: 1000000... > ``` More generally, parameters implement a kind of dynamic binding. The [make-parameter](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=parameters.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._make-parameter%2529%2529&version=8.18.0.13) function takes any value and returns a new parameter that is initialized to the given value. Applying the parameter as a function returns its current value: > ```racket > > ( define location ( make-parameter "here" ) ) > > ( location ) > "here" > ```
# 4.7 Conditionals In a [parameterize](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=parameters.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fmore-scheme..rkt%2529._parameterize%2529%2529&version=8.18.0.13) form, each parameter-expr must produce a parameter. During the evaluation of the bodys, each specified parameter is given the result of the corresponding value-expr. When control leaves the [parameterize](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=parameters.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fmore-scheme..rkt%2529._parameterize%2529%2529&version=8.18.0.13) form—either through a normal return, an exception, or some other escape—the parameter reverts to its earlier value: > ```racket > > ( parameterize ( [ location "there" ] ) ( location ) ) > "there" > > ( location ) > "here" > > ( parameterize ( [ location "in a house" ] ) ( list ( location ) ( parameterize ( [ location "with a mouse" ] ) ( location ) ) ( location ) ) ) > '("in a house" "with a mouse" "in a house") > > ( parameterize ( [ location "in a box" ] ) ( car ( location ) ) ) > car: contract violation > expected: pair? > given: "in a box" > > ( location ) > "here" > ```
# 4.7 Conditionals The [parameterize](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=parameters.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fmore-scheme..rkt%2529._parameterize%2529%2529&version=8.18.0.13) form is not a binding form like [let](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=let.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fletstx-scheme..rkt%2529._let%2529%2529&version=8.18.0.13); each use of location above refers directly to the original definition. A [parameterize](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=parameters.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fmore-scheme..rkt%2529._parameterize%2529%2529&version=8.18.0.13) form adjusts the value of a parameter during the whole time that the [parameterize](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=parameters.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fmore-scheme..rkt%2529._parameterize%2529%2529&version=8.18.0.13) body is evaluated, even for uses of the parameter that are textually outside of the [parameterize](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=parameters.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fmore-scheme..rkt%2529._parameterize%2529%2529&version=8.18.0.13) body:
# 4.7 Conditionals > ```racket > > ( define ( would-you-could-you? ) ( and ( not ( equal? ( location ) "here" ) ) ( not ( equal? ( location ) "there" ) ) ) ) > > ( would-you-could-you? ) > #f > > ( parameterize ( [ location "on a bus" ] ) ( would-you-could-you? ) ) > #t > ``` If a use of a parameter is textually inside the body of a [parameterize](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=parameters.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fmore-scheme..rkt%2529._parameterize%2529%2529&version=8.18.0.13) but not evaluated before the [parameterize](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=parameters.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fmore-scheme..rkt%2529._parameterize%2529%2529&version=8.18.0.13) form produces a value, then the use does not see the value installed by the [parameterize](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=parameters.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fmore-scheme..rkt%2529._parameterize%2529%2529&version=8.18.0.13) form: > ```racket > > ( let ( [ get ( parameterize ( [ location "with a fox" ] ) ( lambda ( ) ( location ) ) ) ] ) ( get ) ) > "here" > ```
# 4.7 Conditionals The current binding of a parameter can be adjusted imperatively by calling the parameter as a function with a value. If a [parameterize](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=parameters.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fmore-scheme..rkt%2529._parameterize%2529%2529&version=8.18.0.13) has adjusted the value of the parameter, then directly applying the parameter procedure affects only the value associated with the active [parameterize](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=parameters.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fmore-scheme..rkt%2529._parameterize%2529%2529&version=8.18.0.13): > ```racket > > ( define ( try-again! where ) ( location where ) ) > > ( location ) > "here" > > ( parameterize ( [ location "on a train" ] ) ( list ( location ) ( begin ( try-again! "in a boat" ) ( location ) ) ) ) > '("on a train" "in a boat") > > ( location ) > "here" > ```
# 4.7 Conditionals Using [parameterize](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=parameters.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fmore-scheme..rkt%2529._parameterize%2529%2529&version=8.18.0.13) is generally preferable to updating a parameter value imperatively—for much the same reasons that binding a fresh variable with [let](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=let.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fletstx-scheme..rkt%2529._let%2529%2529&version=8.18.0.13) is preferable to using [set!](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=set_.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._set%2521%2529%2529&version=8.18.0.13) (see [Assignment: set!](set_.html)). It may seem that variables and [set!](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=set_.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._set%2521%2529%2529&version=8.18.0.13) can solve many of the same problems that parameters solve. For example, lokation could be defined as a string, and [set!](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=set_.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._set%2521%2529%2529&version=8.18.0.13) could be used to adjust its value:
# 4.7 Conditionals > ```racket > > ( define lokation "here" ) > > ( define ( would-ya-could-ya? ) ( and ( not ( equal? lokation "here" ) ) ( not ( equal? lokation "there" ) ) ) ) > > ( set! lokation "on a bus" ) > > ( would-ya-could-ya? ) > #t > ``` Parameters, however, offer several crucial advantages over [set!](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=set_.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._set%2521%2529%2529&version=8.18.0.13): - The [parameterize](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=parameters.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fmore-scheme..rkt%2529._parameterize%2529%2529&version=8.18.0.13) form helps automatically reset the value of a parameter when control escapes due to an exception. Adding exception handlers and other forms to rewind a [set!](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=set_.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._set%2521%2529%2529&version=8.18.0.13) is relatively tedious.
# 4.7 Conditionals - Parameters work nicely with tail calls (see [Tail Recursion](Lists__Iteration__and_Recursion.html#%28part._tail-recursion%29)). The last body in a [parameterize](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=parameters.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fmore-scheme..rkt%2529._parameterize%2529%2529&version=8.18.0.13) form is in [tail position](Lists__Iteration__and_Recursion.html#%28tech._tail._position%29) with respect to the [parameterize](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=parameters.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fmore-scheme..rkt%2529._parameterize%2529%2529&version=8.18.0.13) form. - Parameters work properly with threads (see [Threads](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=threads.html&version=8.18.0.13)). The [parameterize](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=parameters.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fmore-scheme..rkt%2529._parameterize%2529%2529&version=8.18.0.13) form adjusts the value of a parameter only for evaluation in the current thread, which avoids race conditions with other threads. ------------------------------------------------------------------------
# 5 Programmer-Defined Datatypes
## 5 Programmer-Defined Datatypes > > > <img src="magnify.png" width="24" height="24" alt="+" />[Structures](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=structures.html&version=8.18.0.13) in [The Racket Reference](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=index.html&version=8.18.0.13) also documents structure types. New datatypes are normally created with the [struct](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=define-struct.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._struct%2529%2529&version=8.18.0.13) form, which is the topic of this chapter. The class-based object system, which we defer to [Classes and Objects](classes.html), offers an alternate mechanism for creating new datatypes, but even classes and objects are implemented in terms of structure types.
### 5.1 Simple Structure Types: [struct](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=define-struct.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._struct%2529%2529&version=8.18.0.13) > > > <img src="magnify.png" width="24" height="24" alt="+" />[Defining Structure Types: struct](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=define-struct.html&version=8.18.0.13) in [The Racket Reference](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=index.html&version=8.18.0.13) also documents [struct](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=define-struct.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._struct%2529%2529&version=8.18.0.13). To a first approximation, the syntax of [struct](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=define-struct.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._struct%2529%2529&version=8.18.0.13) is
### 5.1 Simple Structure Types: [struct](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=define-struct.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._struct%2529%2529&version=8.18.0.13) > > | | > > |--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| > > | ([struct](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=define-struct.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._struct%2529%2529&version=8.18.0.13) struct-id (field-id ...)) | Examples: > ([struct](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=define-struct.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._struct%2529%2529&version=8.18.0.13) posn (x y))
### 5.1 Simple Structure Types: [struct](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=define-struct.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._struct%2529%2529&version=8.18.0.13) The [struct](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=define-struct.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._struct%2529%2529&version=8.18.0.13) form binds struct-id and a number of identifiers that are built from struct-id and the field-ids: - struct-id : a constructor function that takes as many arguments as the number of field-ids, and returns an instance of the structure type. Example: > ```racket > > ( posn 1 2 ) > #<posn> > ``` - struct-id? : a predicate function that takes a single argument and returns #t if it is an instance of the structure type, #f otherwise. Examples: > ```racket > > ( posn? 3 ) > #f > > ( posn? ( posn 1 2 ) ) > #t > ``` - struct-id-field-id : for each field-id, an accessor that extracts the value of the corresponding field from an instance of the structure type. Examples: > ```racket > > ( posn-x ( posn 1 2 ) ) > 1 > > ( posn-y ( posn 1 2 ) ) > 2 > ``` - struct:struct-id : a structure type descriptor, which is a value that represents the structure type as a first-class value (with #:super, as discussed later in [More Structure Type Options](#%28part._struct-options%29)).
### 5.1 Simple Structure Types: [struct](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=define-struct.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._struct%2529%2529&version=8.18.0.13) A [struct](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=define-struct.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._struct%2529%2529&version=8.18.0.13) form places no constraints on the kinds of values that can appear for fields in an instance of the structure type. For example, (posn "apple" #f) produces an instance of posn, even though "apple" and #f are not valid coordinates for the obvious uses of posn instances. Enforcing constraints on field values, such as requiring them to be numbers, is normally the job of a contract, as discussed later in [Contracts](contracts.html).
### 5.2 Copying and Update The [struct-copy](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=struct-copy.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._struct-copy%2529%2529&version=8.18.0.13) form clones a structure and optionally updates specified fields in the clone. This process is sometimes called a functional update, because the result is a structure with updated field values. but the original structure is not modified. > > | | > > |-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| > > | ([struct-copy](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=struct-copy.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._struct-copy%2529%2529&version=8.18.0.13) struct-id struct-expr \[field-id expr\] ...) |
### 5.2 Copying and Update The struct-id that appears after [struct-copy](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=struct-copy.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._struct-copy%2529%2529&version=8.18.0.13) must be a structure type name bound by [struct](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=define-struct.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._struct%2529%2529&version=8.18.0.13). The struct-expr must produce an instance of the structure type. The result is a new instance of the structure type that is like the old one, except that the field indicated by each field-id gets the value of the corresponding expr. Examples: > ```racket > > ( define p1 ( posn 1 2 ) ) > > ( define p2 ( struct-copy posn p1 [ x 3 ] ) ) > > ( list ( posn-x p2 ) ( posn-y p2 ) ) > '(3 2) > > ( list ( posn-x p1 ) ( posn-y p1 ) ) > '(1 2) > ```
### 5.3 Structure Subtypes An extended form of [struct](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=define-struct.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._struct%2529%2529&version=8.18.0.13) can be used to define a structure subtype, which is a structure type that extends an existing structure type: > > | | > > |-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| > > | ([struct](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=define-struct.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._struct%2529%2529&version=8.18.0.13) struct-id super-id (field-id ...)) |
### 5.3 Structure Subtypes The super-id must be a structure type name bound by [struct](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=define-struct.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._struct%2529%2529&version=8.18.0.13) (i.e., the name that cannot be used directly as an expression). Examples: > ```racket > ( struct posn ( x y ) ) > ( struct 3d-posn posn ( z ) ) > ``` A structure subtype inherits the fields of its supertype, and the subtype constructor accepts the values for the subtype fields after values for the supertype fields. An instance of a structure subtype can be used with the predicate and accessors of the supertype. Examples: > ```racket > > ( define p ( 3d-posn 1 2 3 ) ) > > p > #<3d-posn> > > ( posn? p ) > #t > > ( 3d-posn-z p ) > 3 > ; a 3d-posn has an x field, but there is no 3d-posn-x selector: > > ( 3d-posn-x p ) > 3d-posn-x: undefined; > cannot reference an identifier before its definition > in module: top-level > ; use the supertype's posn-x selector to access the x field: > > ( posn-x p ) > 1 > ```
### 5.4 Opaque versus Transparent Structure Types With a structure type definition like > ([struct](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=define-struct.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._struct%2529%2529&version=8.18.0.13) posn (x y)) an instance of the structure type prints in a way that does not show any information about the fields’ values. That is, structure types by default are opaque. If the accessors and mutators of a structure type are kept private to a module, then no other module can rely on the representation of the type’s instances. To make a structure type transparent, use the #:transparent keyword after the field-name sequence: > <table data-cellpadding="0" data-cellspacing="0"><colgroup><col style="width: 100%" /></colgroup><tbody><tr><td><pre><code>( struct posn ( x y ) > #:transparent )</code></pre></td></tr><tr><td><p> </p></td></tr><tr><td><pre><code>&gt; ( posn 1 2 ) > (posn 1 2)</code></pre></td></tr></tbody></table>
### 5.4 Opaque versus Transparent Structure Types An instance of a transparent structure type prints like a call to the constructor, so that it shows the structures field values. A transparent structure type also allows reflective operations, such as [struct?](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=structutils.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._struct%7E3f%2529%2529&version=8.18.0.13) and [struct-info](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=inspectors.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._struct-info%2529%2529&version=8.18.0.13), to be used on its instances (see [Reflection and Dynamic Evaluation](reflection.html)). Structure types are opaque by default, because opaque structure instances provide more encapsulation guarantees. That is, a library can use an opaque structure to encapsulate data, and clients of the library cannot manipulate the data in the structure except as allowed by the library.
### 5.5 Structure Comparisons A generic [equal?](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Equality.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._equal%7E3f%2529%2529&version=8.18.0.13) comparison automatically recurs on the fields of a transparent structure type, but [equal?](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Equality.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._equal%7E3f%2529%2529&version=8.18.0.13) defaults to mere instance identity for opaque structure types: > <table data-cellpadding="0" data-cellspacing="0"><colgroup><col style="width: 100%" /></colgroup><tbody><tr><td>([struct](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=define-struct.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._struct%2529%2529&version=8.18.0.13) glass (width height) #:transparent)</td></tr><tr><td><p> </p></td></tr><tr><td><pre><code>&gt; ( equal? ( glass 1 2 ) ( glass 1 2 ) ) > #t</code></pre></td></tr></tbody></table>
### 5.5 Structure Comparisons > <table data-cellpadding="0" data-cellspacing="0"><colgroup><col style="width: 100%" /></colgroup><tbody><tr><td>([struct](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=define-struct.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._struct%2529%2529&version=8.18.0.13) lead (width height))</td></tr><tr><td><p> </p></td></tr><tr><td><pre><code>&gt; ( define slab ( lead 1 2 ) ) > &gt; ( equal? slab slab ) > #t > &gt; ( equal? slab ( lead 1 2 ) ) > #f</code></pre></td></tr></tbody></table> To support instances comparisons via [equal?](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Equality.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._equal%7E3f%2529%2529&version=8.18.0.13) without making the structure type transparent, you can use the #:methods keyword, [gen:equal+hash](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Equality.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._gen%7E3aequal%252Bhash%2529%2529&version=8.18.0.13), and implement three methods: > ``` (struct lead (width height)
### 5.5 Structure Comparisons > #:methods > gen:equal+hash > [ ( define ( equal-proc a b equal?-recur ) > ; compare a and b > ( and ( equal?-recur ( lead-width a ) ( lead-width b ) ) > ( equal?-recur ( lead-height a ) ( lead-height b ) ) ) ) > ( define ( hash-proc a hash-recur ) > ; compute primary hash code of a > ( + ( hash-recur ( lead-width a ) ) > ( * 3 ( hash-recur ( lead-height a ) ) ) ) ) > ( define ( hash2-proc a hash2-recur ) > ; compute secondary hash code of a > ( + ( hash2-recur ( lead-width a ) ) > ( hash2-recur ( lead-height a ) ) ) ) ] ) > ( equal? ( lead 1 2 ) ( lead 1 2 ) ) > #t
### 5.5 Structure Comparisons ``` The first function in the list implements the equal? test on two leads; the third argument to the function is used instead of equal? for recursive equality testing, so that data cycles can be handled correctly. The other two functions compute primary and secondary hash codes for use with hash tables: > ```racket > > ( define h ( make-hash ) ) > > ( hash-set! h ( lead 1 2 ) 3 ) > > ( hash-ref h ( lead 1 2 ) ) > 3 > > ( hash-ref h ( lead 2 1 ) ) > hash-ref: no value found for key > key: #<lead> > ``` The first function provided with gen:equal+hash is not required to recursively compare the fields of the structure. For example, a structure type representing a set might implement equality by checking that the members of the set are the same, independent of the order of elements in the internal representation. Just take care that the hash functions produce the same value for any two structure types that are supposed to be equivalent. ### 5.6 Structure Type Generativity Each time that a struct form is evaluated, it generates a structure type that is distinct from all existing structure types, even if some other structure type has the same name and fields. This generativity is useful for enforcing abstractions and implementing programs such as interpreters, but beware of placing a struct form in positions that are evaluated multiple times. Examples: > ```racket > ( define ( add-bigger-fish lst ) ( struct fish ( size ) #:transparent ) ; new every time ( cond [ ( null? lst ) ( list ( fish 1 ) ) ] [ else ( cons ( fish ( * 2 ( fish-size ( car lst ) ) ) ) lst ) ] ) ) > > ( add-bigger-fish null ) > (list (fish 1)) > > ( add-bigger-fish ( add-bigger-fish null ) ) > fish-size: contract violation > expected: fish? > given: (fish 1) > ``` > ``` (struct fish (size) #:transparent) > ( define ( add-bigger-fish lst ) > ( cond > [ ( null? lst ) ( list ( fish 1 ) ) ] > [ else ( cons ( fish ( * 2 ( fish-size ( car lst ) ) ) ) > lst ) ] ) )   > ( add-bigger-fish ( add-bigger-fish null ) ) > (list (fish 2) (fish 1))``` ### 5.7 Prefab Structure Types Although a [transparent](#%28tech._transparent%29) structure type prints in a way that shows its content, the printed form of the structure cannot be used in an expression to get the structure back, unlike the printed form of a number, string, symbol, or list. A prefab (“previously fabricated”) structure type is a built-in type that is known to the Racket printer and expression reader. Infinitely many such types exist, and they are indexed by name, field count, supertype, and other such details. The printed form of a prefab structure is similar to a vector, but it starts #s instead of just #, and the first element in the printed form is the prefab structure type’s name. The following examples show instances of the sprout prefab structure type that has one field. The first instance has a field value 'bean, and the second has field value 'alfalfa: > ```racket > > ' #s ( sprout bean ) > '#s(sprout bean) > > ' #s ( sprout alfalfa ) > '#s(sprout alfalfa) > ``` Like numbers and strings, prefab structures are “self-quoting,” so the quotes above are optional: > ```racket > > #s ( sprout bean ) > '#s(sprout bean) > ``` When you use the #:prefab keyword with [struct](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=define-struct.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._struct%2529%2529&version=8.18.0.13), instead of generating a new structure type, you obtain bindings that work with the existing prefab structure type: > ```racket > > ( define lunch ' #s ( sprout bean ) ) > > ( struct sprout ( kind ) #:prefab ) > > ( sprout? lunch ) > #t > > ( sprout-kind lunch ) > 'bean > > ( sprout ' garlic ) > '#s(sprout garlic) > ``` The field name kind above does not matter for finding the prefab structure type; only the name sprout and the number of fields matter. At the same time, the prefab structure type sprout with three fields is a different structure type than the one with a single field: > ```racket > > ( sprout? #s ( sprout bean #f 17 ) ) > #f > > ( struct sprout ( kind yummy? count ) #:prefab ) ; redefine > > ( sprout? #s ( sprout bean #f 17 ) ) > #t > > ( sprout? lunch ) > #f > ``` A prefab structure type can have another prefab structure type as its supertype, it can have mutable fields, and it can have auto fields. Variations in any of these dimensions correspond to different prefab structure types, and the printed form of the structure type’s name encodes all of the relevant details. > ```racket > > ( struct building ( rooms [ location #:mutable ] ) #:prefab ) > > ( struct house building ( [ occupied #:auto ] ) #:prefab #:auto-value ' no ) > > ( house 5 ' factory ) > '#s((house (1 no) building 2 #(1)) 5 factory no) > ``` Every [prefab](#%28tech._prefab%29) structure type is [transparent](#%28tech._transparent%29)—but even less abstract than a [transparent](#%28tech._transparent%29) type, because instances can be created without any access to a particular structure-type declaration or existing examples. Overall, the different options for structure types offer a spectrum of possibilities from more abstract to more convenient: - [Opaque](#%28tech._opaque%29) (the default) : Instances cannot be inspected or forged without access to the structure-type declaration. As discussed in the next section, [constructor guards](#%28tech._constructor._guard%29) and [properties](#%28tech._property%29) can be attached to the structure type to further protect or to specialize the behavior of its instances. - [Transparent](#%28tech._transparent%29) : Anyone can inspect or create an instance without access to the structure-type declaration, which means that the value printer can show the content of an instance. All instance creation passes through a [constructor guard](#%28tech._constructor._guard%29), however, so that the content of an instance can be controlled, and the behavior of instances can be specialized through [properties](#%28tech._property%29). Since the structure type is generated by its definition, instances cannot be manufactured simply through the name of the structure type, and therefore cannot be generated automatically by the expression reader. - [Prefab](#%28tech._prefab%29) : Anyone can inspect or create an instance at any time, without prior access to a structure-type declaration or an example instance. Consequently, the expression reader can manufacture instances directly. The instance cannot have a [constructor guard](#%28tech._constructor._guard%29) or [properties](#%28tech._property%29). Since the expression reader can generate [prefab](#%28tech._prefab%29) instances, they are useful when convenient [serialization](serialization.html#%28tech._serialization%29) is more important than abstraction. [Opaque](#%28tech._opaque%29) and [transparent](#%28tech._transparent%29) structures also can be serialized, however, if they are defined with [serializable-struct](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=serialization.html%23%2528form._%2528%2528lib._racket%252Fserialize..rkt%2529._serializable-struct%2529%2529&version=8.18.0.13) as described in [Datatypes and Serialization](serialization.html). ### 5.8 More Structure Type Options The full syntax of [struct](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=define-struct.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._struct%2529%2529&version=8.18.0.13) supports many options, both at the structure-type level and at the level of individual fields: > > ``` (struct struct-id maybe-super (field ...) > > struct-option ... )   maybe-super   =       |   super-id           field   =   field-id     |   [field-id field-option ...] ```
### 5.5 Structure Comparisons (find-user-collects-dir) → (-> error type-name "bad name: ~e" name)``` where the name-id is a name for the module, initial-module-path is an initial import, and each decl is an import, export, definition, or expression. In the case of a file, name-id normally matches the name of the containing file, minus its directory path or file extension, but name-id is ignored when the module is [require](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._require%2529%2529&version=8.18.0.13)d through its file’s path.
### 5.5 Structure Comparisons The initial-module-path is needed because even the [require](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._require%2529%2529&version=8.18.0.13) form must be imported for further use in the module body. In other words, the initial-module-path import bootstraps the syntax that is available in the body. The most commonly used initial-module-path is [racket](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=index.html&version=8.18.0.13), which supplies most of the bindings described in this guide, including [require](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._require%2529%2529&version=8.18.0.13), [define](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=define.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._define%2529%2529&version=8.18.0.13), and [provide](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._provide%2529%2529&version=8.18.0.13). Another commonly used initial-module-path is [racket/base](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=index.html&version=8.18.0.13), which provides less functionality, but still much of the most commonly needed functions and syntax.
### 5.5 Structure Comparisons For example, the "cake.rkt" example of the [previous section](module-basics.html) could be written as > ```racket > ( module cake racket > ( provide print-cake ) > ( define ( print-cake n ) > ( show " ~a " n #\. ) > ( show " .-~a-. " n #\| ) > ( show " | ~a | " n #\space ) > ( show "---~a---" n #\- ) ) > ( define ( show fmt n ch ) > ( printf fmt ( make-string n ch ) ) > ( newline ) ) ) > ``` Furthermore, this [module](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=module.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._module%2529%2529&version=8.18.0.13) form can be evaluated in a [REPL](intro.html#%28tech._repl%29) to declare a cake module that is not associated with any file. To refer to such an unassociated module, quote the module name: Examples: > ```racket > > ( require ' cake ) > > ( print-cake 3 ) > ... .-|||-. | | --------- > ```
### 5.5 Structure Comparisons Declaring a module does not immediately evaluate the body definitions and expressions of the module. The module must be explicitly [require](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._require%2529%2529&version=8.18.0.13)d at the top level to trigger evaluation. After evaluation is triggered once, later [require](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._require%2529%2529&version=8.18.0.13)s do not re-evaluate the module body. Examples: > ```racket > > ( module hi racket ( printf "Hello\n" ) ) > > ( require ' hi ) > Hello > > ( require ' hi ) > ```
#### 6.2.2 The #lang Shorthand The body of a #lang shorthand has no specific syntax, because the syntax is determined by the language name that follows #lang. In the case of #lang [racket](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=index.html&version=8.18.0.13), the syntax is > ```racket > #lang racket > decl ... > ``` which [reads](hash-lang_reader.html) the same as > ```racket > ( module name racket > decl ... ) > ``` where name is derived from the name of the file that contains the #lang form. The #lang [racket/base](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=index.html&version=8.18.0.13) form has the same syntax as #lang [racket](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=index.html&version=8.18.0.13), except that the longhand expansion uses [racket/base](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=index.html&version=8.18.0.13) instead of [racket](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=index.html&version=8.18.0.13). The #lang [scribble/manual](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=scribble&rel=manual.html&version=8.18.0.13) form, in contrast, has a completely different syntax that doesn’t even look like Racket, and which we do not attempt to describe in this guide.
### 5.5 Structure Comparisons Unless otherwise specified, a module that is documented as a “language” using the #lang notation will expand to [module](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=module.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._module%2529%2529&version=8.18.0.13) in the same way as #lang [racket](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=index.html&version=8.18.0.13). The documented language name can be used directly with [module](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=module.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._module%2529%2529&version=8.18.0.13) or [require](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._require%2529%2529&version=8.18.0.13), too.
#### 6.2.3 Submodules A [module](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=module.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._module%2529%2529&version=8.18.0.13) form can be nested within a module, in which case the nested [module](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=module.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._module%2529%2529&version=8.18.0.13) form declares a submodule. Submodules can be referenced directly by the enclosing module using a quoted name. The following example prints "Tony" by importing tiger from the zoo submodule: > > "park.rkt" > > > > > ```racket > > > #lang racket > > > ( module zoo racket > > > ( provide tiger ) > > > ( define tiger "Tony" ) ) > > > ( require ' zoo ) > > > tiger > > > ``` Running a module does not necessarily run its submodules. In the above example, running "park.rkt" runs its submodule zoo only because the "park.rkt" module [require](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._require%2529%2529&version=8.18.0.13)s the zoo submodule. Otherwise, a module and each of its submodules can be run independently. Furthermore, if "park.rkt" is compiled to a bytecode file (via raco make), then the code for "park.rkt" or the code for zoo can be loaded independently.
### 5.5 Structure Comparisons Submodules can be nested within submodules, and a submodule can be referenced directly by a module other than its enclosing module by using a [submodule path](module-paths.html#%28elem._submod%29). A [module*](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=module.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._module%252A%2529%2529&version=8.18.0.13) form is similar to a nested [module](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=module.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._module%2529%2529&version=8.18.0.13) form: > > ``` (module* name-id initial-module-path-or-#f > > decl ... )
### 5.5 Structure Comparisons ``` The module* form differs from module in that it inverts the possibilities for reference between the submodule and enclosing module: - A submodule declared with module can be required by its enclosing module, but the submodule cannot require the enclosing module or lexically reference the enclosing module’s bindings. - A submodule declared with module* can require its enclosing module, but the enclosing module cannot require the submodule. In addition, a module* form can specify #f in place of an initial-module-path, in which case the submodule sees all of the enclosing module’s bindings—including bindings that are not exported via provide. One use of submodules declared with module* and #f is to export additional bindings through a submodule that are not normally exported from the module: > > "cake.rkt" > > > > > ```racket > > > #lang racket > > > ( provide print-cake ) > > > ( define ( print-cake n ) > > > ( show " ~a " n #\. ) > > > ( show " .-~a-. " n #\| ) > > > ( show " | ~a | " n #\space ) > > > ( show "---~a---" n #\- ) ) > > > ( define ( show fmt n ch ) > > > ( printf fmt ( make-string n ch ) ) > > > ( newline ) ) > > > ( module* extras #f > > > ( provide show ) ) > > > ``` In this revised "cake.rkt" module, show is not imported by a module that uses (require "cake.rkt"), since most clients of "cake.rkt" will not want the extra function. A module can require the extra submodule using (require (submod "cake.rkt" extras)) to access the otherwise hidden show function.See submodule paths for more information on submod. #### 6.2.4 Main and Test Submodules The following variant of "cake.rkt" includes a main submodule that calls print-cake: > > "cake.rkt" > > > > > ```racket > > > #lang racket > > > ( define ( print-cake n ) > > > ( show " ~a " n #\. ) > > > ( show " .-~a-. " n #\| ) > > > ( show " | ~a | " n #\space ) > > > ( show "---~a---" n #\- ) ) > > > ( define ( show fmt n ch ) > > > ( printf fmt ( make-string n ch ) ) > > > ( newline ) ) > > > ( module* main #f > > > ( print-cake 10 ) ) > > > ``` Running a module does not run its module*-defined submodules. Nevertheless, running the above module via racket or DrRacket prints a cake with 10 candles, because the main submodule is a special case. When a module is provided as a program name to the racket executable or run directly within DrRacket, if the module has a main submodule, the main submodule is run after its enclosing module. Declaring a main submodule thus specifies extra actions to be performed when a module is run directly, instead of required as a library within a larger program. A main submodule does not have to be declared with module*. If the main module does not need to use bindings from its enclosing module, it can be declared with module. More commonly, main is declared using module+: > > ``` (module+ name-id > > decl ... )``` A submodule declared with [module+](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=module.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._module%252B%2529%2529&version=8.18.0.13) is like one declared with [module*](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=module.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._module%252A%2529%2529&version=8.18.0.13) using #f as its initial-module-path. In addition, multiple [module+](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=module.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._module%252B%2529%2529&version=8.18.0.13) forms can specify the same submodule name, in which case the bodies of the [module+](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=module.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._module%252B%2529%2529&version=8.18.0.13) forms are combined to create a single submodule. The combining behavior of [module+](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=module.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._module%252B%2529%2529&version=8.18.0.13) is particularly useful for defining a test submodule, which can be conveniently run using raco test in much the same way that main is conveniently run with racket. For example, the following "physics.rkt" module exports drop and to-energy functions, and it defines a test module to hold unit tests: > > "physics.rkt" > > > > > ```racket > > > #lang racket > > > ( module+ test > > > ( require rackunit ) > > > ( define ε 1e-10 ) ) > > > ( provide drop > > > to-energy ) > > > ( define ( drop t ) > > > ( * 1/2 9.8 t t ) ) > > > ( module+ test > > > ( check-= ( drop 0 ) 0 ε ) > > > ( check-= ( drop 10 ) 490 ε ) ) > > > ( define ( to-energy m ) > > > ( * m ( expt 299792458.0 2 ) ) ) > > > ( module+ test > > > ( check-= ( to-energy 0 ) 0 ε ) > > > ( check-= ( to-energy 1 ) 9e+16 1e+15 ) ) > > > ``` Importing "physics.rkt" into a larger program does not run the drop and to-energy tests—or even trigger the loading of the test code, if the module is compiled—but running raco test physics.rkt at a command line runs the tests. The above "physics.rkt" module is equivalent to using [module*](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=module.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._module%252A%2529%2529&version=8.18.0.13): > > "physics.rkt" > > > > > ```racket > > > #lang racket > > > ( provide drop > > > to-energy ) > > > ( define ( drop t ) > > > ( * 1/2 49/5 t t ) ) > > > ( define ( to-energy m ) > > > ( * m ( expt 299792458 2 ) ) ) > > > ( module* test #f > > > ( require rackunit ) > > > ( define ε 1e-10 ) > > > ( check-= ( drop 0 ) 0 ε ) > > > ( check-= ( drop 10 ) 490 ε ) > > > ( check-= ( to-energy 0 ) 0 ε ) > > > ( check-= ( to-energy 1 ) 9e+16 1e+15 ) ) > > > ``` Using [module+](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=module.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._module%252B%2529%2529&version=8.18.0.13) instead of [module*](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=module.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._module%252A%2529%2529&version=8.18.0.13) allows tests to be interleaved with function definitions. The combining behavior of [module+](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=module.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._module%252B%2529%2529&version=8.18.0.13) is also sometimes helpful for a main module. Even when combining is not needed, ([module+](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=module.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._module%252B%2529%2529&version=8.18.0.13) main ....) is preferred as it is more readable than ([module*](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=module.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._module%252A%2529%2529&version=8.18.0.13) main #f ....). ------------------------------------------------------------------------ # 6.3 Module Paths ### 6.3 Module Paths A module path is a reference to a module, as used with [require](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._require%2529%2529&version=8.18.0.13) or as the initial-module-path in a [module](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=module.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._module%2529%2529&version=8.18.0.13) form. It can be any of several forms: > > | | > > |----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| > > | ([quote](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=quote.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._quote%2529%2529&version=8.18.0.13) id) | > > A [module path](#%28tech._module._path%29) that is a quoted identifier refers to a non-file [module](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=module.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._module%2529%2529&version=8.18.0.13) declaration using the identifier. This form of module reference makes the most sense in a [REPL](intro.html#%28tech._repl%29). > > > > Examples: > > > > > > > ```racket > > > ( module m racket ( provide color ) ( define color "blue" ) ) > > > ( module n racket ( require ' m ) ( printf "my favorite color is ~a\n" color ) ) > > > ( require ' n ) > > my favorite color is blue > > ``` > > > > | | > > |------------| > > | rel-string | > > A string [module path](#%28tech._module._path%29) is a relative path using Unix-style conventions: / is the path separator, .. refers to the parent directory, and . refers to the same directory. The rel-string must not start or end with a path separator. > > The path is relative to the enclosing file, if any, or it is relative to the current directory. (More precisely, the path is relative to the value of ([current-load-relative-directory](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=eval.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._current-load-relative-directory%2529%2529&version=8.18.0.13)), which is set while loading a file.) > > [Module Basics](module-basics.html) shows examples using relative paths. > > If a relative path ends with a ".ss" suffix, it is converted to ".rkt". If the file that implements the referenced module actually ends in ".ss", the suffix will be changed back when attempting to load the file (but a ".rkt" suffix takes precedence). This two-way conversion provides compatibility with older versions of Racket. > > | | > > |-----| > > | id | > > A [module path](#%28tech._module._path%29) that is an unquoted identifier refers to an installed library. The id is constrained to contain only ASCII letters, ASCII numbers, +, -, \_, and /, where / separates path elements within the identifier. The elements refer to [collection](module-basics.html#%28tech._collection%29)s and sub-[collections](module-basics.html#%28tech._collection%29), instead of directories and sub-directories. > > An example of this form is racket/date. It refers to the module whose source is the "date.rkt" file in the "racket" collection, which is installed as part of Racket. The ".rkt" suffix is added automatically. > > Another example of this form is [racket](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=index.html&version=8.18.0.13), which is commonly used at the initial import. The path [racket](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=index.html&version=8.18.0.13) is shorthand for racket/main; when an id has no /, then /main is automatically added to the end. Thus, [racket](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=index.html&version=8.18.0.13) or racket/main refers to the module whose source is the "main.rkt" file in the "racket" collection. > > > > Examples: > > > > > > > ```racket > > > ( module m racket ( require racket/date ) ( printf "Today is ~s\n" ( date->string ( seconds->date ( current-seconds ) ) ) ) ) > > > ( require ' m ) > > Today is "Monday, September 1st, 2025" > > ``` > > > > When the full path of a module ends with ".rkt", if no such file exists but one does exist with the ".ss" suffix, then the ".ss" suffix is substituted automatically. This transformation provides compatibility with older versions of Racket. > > | | > > |------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| > > | ([lib](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._lib%2529%2529&version=8.18.0.13) rel-string) | > > Like an unquoted-identifier path, but expressed as a string instead of an identifier. Also, the rel-string can end with a file suffix, in which case ".rkt" is not automatically added. > > Example of this form include ([lib](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._lib%2529%2529&version=8.18.0.13) "racket/date.rkt") and ([lib](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._lib%2529%2529&version=8.18.0.13) "racket/date"), which are equivalent to racket/date. Other examples include ([lib](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._lib%2529%2529&version=8.18.0.13) "racket"), ([lib](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._lib%2529%2529&version=8.18.0.13) "racket/main"), and ([lib](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._lib%2529%2529&version=8.18.0.13) "racket/main.rkt"), which are all equivalent to [racket](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=index.html&version=8.18.0.13). > > > > Examples: > > > > > > > ```racket > > > ( module m ( lib "racket" ) ( require ( lib "racket/date.rkt" ) ) ( printf "Today is ~s\n" ( date->string ( seconds->date ( current-seconds ) ) ) ) ) > > > ( require ' m ) > > Today is "Monday, September 1st, 2025" > > ``` > > > > | | > > |----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| > > | ([planet](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._planet%2529%2529&version=8.18.0.13) id) | > > Accesses a third-party library that is distributed through the PLaneT server. The library is downloaded the first time that it is needed, and then the local copy is used afterward. > > The id encodes several pieces of information separated by a /: the package owner, then package name with optional version information, and an optional path to a specific library with the package. Like id as shorthand for a [lib](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._lib%2529%2529&version=8.18.0.13) path, a ".rkt" suffix is added automatically, and /main is used as the path if no sub-path element is supplied. > > > > Examples: > > > > > > > ```racket > > > ( module m ( lib "racket" ) ; Use "schematics" ' s "random.plt" 1.0, file "random.rkt" : ( require ( planet schematics/random:1/random ) ) ( display ( random-gaussian ) ) ) > > > ( require ' m ) > > 0.9050686838895684 > > ``` > > > > As with other forms, an implementation file ending with ".ss" can be substituted automatically if no implementation file ending with ".rkt" exists. > > | | > > |----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| > > | ([planet](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._planet%2529%2529&version=8.18.0.13) package-string) | > > Like the symbol form of a [planet](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._planet%2529%2529&version=8.18.0.13), but using a string instead of an identifier. Also, the package-string can end with a file suffix, in which case ".rkt" is not added. > > As with other forms, an ".ss" extension is converted to ".rkt", while an implementation file ending with ".ss" can be substituted automatically if no implementation file ending with ".rkt" exists. > > <table data-cellpadding="0" data-cellspacing="0"><colgroup><col style="width: 100%" /></colgroup><tbody><tr><td>([planet](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._planet%2529%2529&version=8.18.0.13) rel-string (user-string pkg-string vers ...))</td></tr><tr><td> </td></tr><tr><td><table data-cellpadding="0" data-cellspacing="0"><tbody><tr><td style="text-align: right;" data-valign="baseline">vers</td><td style="text-align: left;" data-valign="baseline"> </td><td style="text-align: center;" data-valign="baseline">=</td><td style="text-align: left;" data-valign="baseline"> </td><td style="text-align: left;" data-valign="baseline">nat</td></tr><tr><td style="text-align: right;" data-valign="baseline"> </td><td style="text-align: left;" data-valign="baseline"> </td><td style="text-align: center;" data-valign="baseline">|</td><td style="text-align: left;" data-valign="baseline"> </td><td style="text-align: left;" data-valign="baseline">(nat nat)</td></tr><tr><td style="text-align: right;" data-valign="baseline"> </td><td style="text-align: left;" data-valign="baseline"> </td><td style="text-align: center;" data-valign="baseline">|</td><td style="text-align: left;" data-valign="baseline"> </td><td style="text-align: left;" data-valign="baseline">([=](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=generic-numbers.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._%7E3d%2529%2529&version=8.18.0.13) nat)</td></tr><tr><td style="text-align: right;" data-valign="baseline"> </td><td style="text-align: left;" data-valign="baseline"> </td><td style="text-align: center;" data-valign="baseline">|</td><td style="text-align: left;" data-valign="baseline"> </td><td style="text-align: left;" data-valign="baseline">([+](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=generic-numbers.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._%252B%2529%2529&version=8.18.0.13) nat)</td></tr><tr><td style="text-align: right;" data-valign="baseline"> </td><td style="text-align: left;" data-valign="baseline"> </td><td style="text-align: center;" data-valign="baseline">|</td><td style="text-align: left;" data-valign="baseline"> </td><td style="text-align: left;" data-valign="baseline">([-](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=generic-numbers.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._-%2529%2529&version=8.18.0.13) nat)</td></tr></tbody></table></td></tr></tbody></table> > > A more general form to access a library from the PLaneT server. In this general form, a PLaneT reference starts like a [lib](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._lib%2529%2529&version=8.18.0.13) reference with a relative path, but the path is followed by information about the producer, package, and version of the library. The specified package is downloaded and installed on demand. > > The verses specify a constraint on the acceptable version of the package, where a version number is a sequence of non-negative integers, and the constraints determine the allowable values for each element in the sequence. If no constraint is provided for a particular element, then any version is allowed; in particular, omitting all verses means that any version is acceptable. Specifying at least one vers is strongly recommended. > > For a version constraint, a plain nat is the same as ([+](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=generic-numbers.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._%252B%2529%2529&version=8.18.0.13) nat), which matches nat or higher for the corresponding element of the version number. A (start-nat end-nat) matches any number in the range start-nat to end-nat, inclusive. A ([=](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=generic-numbers.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._%7E3d%2529%2529&version=8.18.0.13) nat) matches only exactly nat. A ([-](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=generic-numbers.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._-%2529%2529&version=8.18.0.13) nat) matches nat or lower. > > > > Examples: > > > > > > > ```racket > > > ( module m ( lib "racket" ) ( require ( planet "random.rkt" ( "schematics" "random.plt" 1 0 ) ) ) ( display ( random-gaussian ) ) ) > > > ( require ' m ) > > 0.9050686838895684 > > ``` > > > > The automatic ".ss" and ".rkt" conversions apply as with other forms. > > | | > > |----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| > > | ([file](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._file%2529%2529&version=8.18.0.13) string) | > > Refers to a file, where string is a relative or absolute path using the current platform’s conventions. This form is not portable, and it should not be used when a plain, portable rel-string suffices. > > The automatic ".ss" and ".rkt" conversions apply as with other forms. > > <table data-cellpadding="0" data-cellspacing="0"><colgroup><col style="width: 100%" /></colgroup><tbody><tr><td>([submod](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._submod%2529%2529&version=8.18.0.13) base element ...+)</td></tr><tr><td> </td></tr><tr><td><table data-cellpadding="0" data-cellspacing="0"><tbody><tr><td style="text-align: right;" data-valign="baseline">base</td><td style="text-align: left;" data-valign="baseline"> </td><td style="text-align: center;" data-valign="baseline">=</td><td style="text-align: left;" data-valign="baseline"> </td><td style="text-align: left;" data-valign="baseline">module-path</td></tr><tr><td style="text-align: right;" data-valign="baseline"> </td><td style="text-align: left;" data-valign="baseline"> </td><td style="text-align: center;" data-valign="baseline">|</td><td style="text-align: left;" data-valign="baseline"> </td><td style="text-align: left;" data-valign="baseline">"."</td></tr><tr><td style="text-align: right;" data-valign="baseline"> </td><td style="text-align: left;" data-valign="baseline"> </td><td style="text-align: center;" data-valign="baseline">|</td><td style="text-align: left;" data-valign="baseline"> </td><td style="text-align: left;" data-valign="baseline">".."</td></tr><tr><td style="text-align: right;" data-valign="baseline"> </td><td style="text-align: left;" data-valign="baseline"> </td><td style="text-align: center;" data-valign="baseline"> </td><td style="text-align: left;" data-valign="baseline"> </td><td style="text-align: left;" data-valign="baseline"> </td></tr><tr><td style="text-align: right;" data-valign="baseline">element</td><td style="text-align: left;" data-valign="baseline"> </td><td style="text-align: center;" data-valign="baseline">=</td><td style="text-align: left;" data-valign="baseline"> </td><td style="text-align: left;" data-valign="baseline">id</td></tr><tr><td style="text-align: right;" data-valign="baseline"> </td><td style="text-align: left;" data-valign="baseline"> </td><td style="text-align: center;" data-valign="baseline">|</td><td style="text-align: left;" data-valign="baseline"> </td><td style="text-align: left;" data-valign="baseline">".."</td></tr></tbody></table></td></tr></tbody></table> > > Refers to a submodule of base. The sequence of elements within [submod](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._submod%2529%2529&version=8.18.0.13) specify a path of submodule names to reach the final submodule. > > > > Examples: > > > > > > > ```racket > > > ( module zoo racket ( module monkey-house racket ( provide monkey ) ( define monkey "Curious George" ) ) ) > > > ( require ( submod ' zoo monkey-house ) ) > > > monkey > > "Curious George" > > ``` > > > > Using "." as base within [submod](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._submod%2529%2529&version=8.18.0.13) stands for the enclosing module. Using ".." as base is equivalent to using "." followed by an extra "..". When a path of the form ([quote](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=quote.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._quote%2529%2529&version=8.18.0.13) id) refers to a submodule, it is equivalent to ([submod](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._submod%2529%2529&version=8.18.0.13) "." id). > > Using ".." as an element cancels one submodule step, effectively referring to the enclosing module. For example, ([submod](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._submod%2529%2529&version=8.18.0.13) "..") refers to the enclosing module of the submodule in which the path appears. > > > > Examples: > > > > > > > ```racket > > > ( module zoo racket ( module monkey-house racket ( provide monkey ) ( define monkey "Curious George" ) ) ( module crocodile-house racket ( require ( submod ".." monkey-house ) ) ( provide dinner ) ( define dinner monkey ) ) ) > > > ( require ( submod ' zoo crocodile-house ) ) > > > dinner > > "Curious George" > > ``` > > ------------------------------------------------------------------------ # 6.4 Imports: require ### 6.4 Imports: [require](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._require%2529%2529&version=8.18.0.13) The [require](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._require%2529%2529&version=8.18.0.13) form imports from another module. A [require](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._require%2529%2529&version=8.18.0.13) form can appear within a module, in which case it introduces bindings from the specified module into the importing module. A [require](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._require%2529%2529&version=8.18.0.13) form can also appear at the top level, in which case it both imports bindings and instantiates the specified module; that is, it evaluates the body definitions and expressions of the specified module, if they have not been evaluated already. A single [require](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._require%2529%2529&version=8.18.0.13) can specify multiple imports at once: > > | | > > |--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| > > | ([require](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._require%2529%2529&version=8.18.0.13) require-spec ...) | Specifying multiple require-specs in a single [require](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._require%2529%2529&version=8.18.0.13) is essentially the same as using multiple [require](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._require%2529%2529&version=8.18.0.13)s, each with a single require-spec. The difference is minor, and confined to the top-level: a single [require](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._require%2529%2529&version=8.18.0.13) can import a given identifier at most once, whereas a separate [require](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._require%2529%2529&version=8.18.0.13) can replace the bindings of a previous [require](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._require%2529%2529&version=8.18.0.13) (both only at the top level, outside of a module). The allowed shape of a require-spec is defined recursively: > > > | | > > > |-------------| > > > | module-path | > > > > In its simplest form, a require-spec is a module-path (as defined in the previous section, [Module Paths](module-paths.html)). In this case, the bindings introduced by [require](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._require%2529%2529&version=8.18.0.13) are determined by [provide](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._provide%2529%2529&version=8.18.0.13) declarations within each module referenced by each module-path. > > > > > > > > Examples: > > > > > > > > > > > > > ```racket > > > > ( module m racket ( provide color ) ( define color "blue" ) ) > > > > ( module n racket ( provide size ) ( define size 17 ) ) > > > > ( require ' m ' n ) > > > > ( list color size ) > > > '("blue" 17) > > > ``` > > > > > > > <table data-cellpadding="0" data-cellspacing="0"><colgroup><col style="width: 100%" /></colgroup><tbody><tr><td>([only-in](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._only-in%2529%2529&version=8.18.0.13) require-spec id-maybe-renamed ...)</td></tr><tr><td> </td></tr><tr><td><table data-cellpadding="0" data-cellspacing="0"><tbody><tr><td style="text-align: right;" data-valign="baseline">id-maybe-renamed</td><td style="text-align: left;" data-valign="baseline"> </td><td style="text-align: center;" data-valign="baseline">=</td><td style="text-align: left;" data-valign="baseline"> </td><td style="text-align: left;" data-valign="baseline">id</td></tr><tr><td style="text-align: right;" data-valign="baseline"> </td><td style="text-align: left;" data-valign="baseline"> </td><td style="text-align: center;" data-valign="baseline">|</td><td style="text-align: left;" data-valign="baseline"> </td><td style="text-align: left;" data-valign="baseline">[orig-id bind-id]</td></tr></tbody></table></td></tr></tbody></table> > > > > An [only-in](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._only-in%2529%2529&version=8.18.0.13) form limits the set of bindings that would be introduced by a base require-spec. Also, [only-in](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._only-in%2529%2529&version=8.18.0.13) optionally renames each binding that is preserved: in a \[orig-id bind-id\] form, the orig-id refers to a binding implied by require-spec, and bind-id is the name that will be bound in the importing context instead of orig-id. > > > > > > > > Examples: > > > > > > > > > > > > > ```racket > > > > ( module m ( lib "racket" ) ( provide tastes-great? less-filling? ) ( define tastes-great? #t ) ( define less-filling? #t ) ) > > > > ( require ( only-in ' m tastes-great? ) ) > > > > tastes-great? > > > #t > > > > less-filling? > > > less-filling?: undefined; > > > cannot reference an identifier before its definition > > > in module: top-level > > > > ( require ( only-in ' m [ less-filling? lite? ] ) ) > > > > lite? > > > #t > > > ``` > > > > > > > | | > > > |---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| > > > | ([except-in](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._except-in%2529%2529&version=8.18.0.13) require-spec id ...) | > > > > This form is the complement of [only-in](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._only-in%2529%2529&version=8.18.0.13): it excludes specific bindings from the set specified by require-spec. > > > | | > > > |--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| > > > | ([rename-in](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._rename-in%2529%2529&version=8.18.0.13) require-spec \[orig-id bind-id\] ...) | > > > > This form supports renaming like [only-in](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._only-in%2529%2529&version=8.18.0.13), but leaving alone identifiers from require-spec that are not mentioned as an orig-id. > > > | | > > > |------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| > > > | ([prefix-in](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._prefix-in%2529%2529&version=8.18.0.13) prefix-id require-spec) | > > > > This is a shorthand for renaming, where prefix-id is added to the front of each identifier specified by require-spec. The [only-in](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._only-in%2529%2529&version=8.18.0.13), [except-in](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._except-in%2529%2529&version=8.18.0.13), [rename-in](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._rename-in%2529%2529&version=8.18.0.13), and [prefix-in](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._prefix-in%2529%2529&version=8.18.0.13) forms can be nested to implement more complex manipulations of imported bindings. For example, > ([require](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._require%2529%2529&version=8.18.0.13) ([prefix-in](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._prefix-in%2529%2529&version=8.18.0.13) m: ([except-in](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._except-in%2529%2529&version=8.18.0.13) 'm ghost))) imports all bindings that m exports, except for the ghost binding, and with local names that are prefixed with m:. Equivalently, the [prefix-in](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._prefix-in%2529%2529&version=8.18.0.13) could be applied before [except-in](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._except-in%2529%2529&version=8.18.0.13), as long as the omission with [except-in](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._except-in%2529%2529&version=8.18.0.13) is specified using the m: prefix: > ([require](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._require%2529%2529&version=8.18.0.13) ([except-in](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._except-in%2529%2529&version=8.18.0.13) ([prefix-in](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._prefix-in%2529%2529&version=8.18.0.13) m: 'm) m:ghost)) ------------------------------------------------------------------------ # 6.5 Exports: provide ### 6.5 Exports: [provide](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._provide%2529%2529&version=8.18.0.13) By default, all of a module’s definitions are private to the module. The [provide](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._provide%2529%2529&version=8.18.0.13) form specifies definitions to be made available where the module is [require](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._require%2529%2529&version=8.18.0.13)d. > > | | > > |--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| > > | ([provide](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._provide%2529%2529&version=8.18.0.13) provide-spec ...) | A [provide](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._provide%2529%2529&version=8.18.0.13) form can only appear at module level (i.e., in the immediate body of a [module](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=module.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._module%2529%2529&version=8.18.0.13)). Specifying multiple provide-specs in a single [provide](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._provide%2529%2529&version=8.18.0.13) is exactly the same as using multiple [provide](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._provide%2529%2529&version=8.18.0.13)s each with a single provide-spec. Each identifier can be exported at most once from a module across all [provide](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._provide%2529%2529&version=8.18.0.13)s within the module. More precisely, the external name for each export must be distinct; the same internal binding can be exported multiple times with different external names. The allowed shape of a provide-spec is defined recursively: > > > | | > > > |------------| > > > | identifier | > > > > In its simplest form, a provide-spec indicates a binding within its module to be exported. The binding can be from either a local definition, or from an import. > > > | | > > > |-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| > > > | ([rename-out](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._rename-out%2529%2529&version=8.18.0.13) \[orig-id export-id\] ...) | > > > > A [rename-out](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._rename-out%2529%2529&version=8.18.0.13) form is similar to just specifying an identifier, but the exported binding orig-id is given a different name, export-id, to importing modules. > > > | | > > > |-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| > > > | ([struct-out](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._struct-out%2529%2529&version=8.18.0.13) struct-id) | > > > > A [struct-out](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._struct-out%2529%2529&version=8.18.0.13) form exports the bindings created by ([struct](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=define-struct.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._struct%2529%2529&version=8.18.0.13) struct-id ....). > > > > > > > <img src="finger.png" width="24" height="24" alt="+" />See [Programmer-Defined Datatypes](define-struct.html) for information on [define-struct](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=define-struct.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._define-struct%2529%2529&version=8.18.0.13). > > > | | > > > |-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| > > > | ([all-defined-out](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._all-defined-out%2529%2529&version=8.18.0.13)) | > > > > The [all-defined-out](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._all-defined-out%2529%2529&version=8.18.0.13) shorthand exports all bindings that are defined within the exporting module (as opposed to imported). > > > > Use of the [all-defined-out](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._all-defined-out%2529%2529&version=8.18.0.13) shorthand is generally discouraged, because it makes less clear the actual exports for a module, and because Racket programmers get into the habit of thinking that definitions can be added freely to a module without affecting its public interface (which is not the case when [all-defined-out](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._all-defined-out%2529%2529&version=8.18.0.13) is used). > > > | | > > > |-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| > > > | ([all-from-out](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._all-from-out%2529%2529&version=8.18.0.13) module-path) | > > > > The [all-from-out](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._all-from-out%2529%2529&version=8.18.0.13) shorthand exports all bindings in the module that were imported using a require-spec that is based on module-path. > > > > Although different module-paths could refer to the same file-based module, re-exporting with [all-from-out](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._all-from-out%2529%2529&version=8.18.0.13) is based specifically on the module-path reference, and not the module that is actually referenced. > > > | | > > > |-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| > > > | ([except-out](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._except-out%2529%2529&version=8.18.0.13) provide-spec id ...) | > > > > Like provide-spec, but omitting the export of each id, where id is the external name of the binding to omit. > > > | | > > > |--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| > > > | ([prefix-out](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._prefix-out%2529%2529&version=8.18.0.13) prefix-id provide-spec) | > > > > Like provide-spec, but adding prefix-id to the beginning of the external name for each exported binding. ------------------------------------------------------------------------ # 6.6 Assignment and Redefinition ### 6.6 Assignment and Redefinition The use of [set!](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=set_.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._set%2521%2529%2529&version=8.18.0.13) on variables defined within a module is limited to the body of the defining module. That is, a module is allowed to change the value of its own definitions, and such changes are visible to importing modules. However, an importing context is not allowed to change the value of an imported binding. Examples: > ```racket > > ( module m racket ( provide counter increment! ) ( define counter 0 ) ( define ( increment! ) ( set! counter ( add1 counter ) ) ) ) > > ( require ' m ) > > counter > 0 > > ( increment! ) > > counter > 1 > > ( set! counter -1 ) > set!: cannot mutate module-required identifier > at: counter > in: (set! counter -1) > ``` As the above example illustrates, a module can always grant others the ability to change its exports by providing a mutator function, such as increment!. The prohibition on assignment of imported variables helps support modular reasoning about programs. For example, in the module, > ```racket > ( module m racket > ( provide rx:fish fishy-string? ) > ( define rx:fish #rx"fish" ) > ( define ( fishy-string? s ) > ( regexp-match? rx:fish s ) ) ) > ``` the function fishy-string? will always match strings that contain “fish”, no matter how other modules use the rx:fish binding. For essentially the same reason that it helps programmers, the prohibition on assignment to imports also allows many programs to be executed more efficiently. Along the same lines, when a module contains no [set!](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=set_.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._set%2521%2529%2529&version=8.18.0.13) of a particular identifier that is defined within the module, then the identifier is considered a constant that cannot be changed—not even by re-declaring the module. Consequently, re-declaration of a module is not generally allowed. For file-based modules, simply changing the file does not lead to a re-declaration in any case, because file-based modules are loaded on demand, and the previously loaded declarations satisfy future requests. It is possible to use Racket’s reflection support to re-declare a module, however, and non-file modules can be re-declared in the [REPL](intro.html#%28tech._repl%29); in such cases, the re-declaration may fail if it involves the re-definition of a previously constant binding. > ```racket > > ( module m racket ( define pie 3.141597 ) ) > > ( require ' m ) > > ( module m racket ( define pie 3 ) ) > define-values: assignment disallowed; > cannot re-define a constant > constant: pie > in module:'m > ``` For exploration and debugging purposes, the Racket reflective layer provides a [compile-enforce-module-constants](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=eval.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._compile-enforce-module-constants%2529%2529&version=8.18.0.13) parameter to disable the enforcement of constants. > ```racket > > ( compile-enforce-module-constants #f ) > > ( module m2 racket ( provide pie ) ( define pie 3.141597 ) ) > > ( require ' m2 ) > > ( module m2 racket ( provide pie ) ( define pie 3 ) ) > > ( compile-enforce-module-constants #t ) > > pie > 3 > ``` ------------------------------------------------------------------------ # 6.7 Modules and Macros ### 6.7 Modules and Macros Racket’s module system cooperates closely with Racket’s [macro](macros.html#%28tech._macro%29) system for adding new syntactic forms to Racket. For example, in the same way that importing [racket/base](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=index.html&version=8.18.0.13) introduces syntax for [require](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._require%2529%2529&version=8.18.0.13) and [lambda](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=lambda.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._lambda%2529%2529&version=8.18.0.13), importing other modules can introduce new syntactic forms (in addition to more traditional kinds of imports, such as functions or constants). We introduce macros in more detail later, in [Macros](macros.html), but here’s a simple example of a module that defines a pattern-based macro: > ```racket > ( module noisy racket > ( provide define-noisy ) > ( define-syntax-rule ( define-noisy ( id arg ... ) body ) > ( define ( id arg ... ) > ( show-arguments ' id ( list arg ... ) ) > body ) ) > ( define ( show-arguments name args ) > ( printf "calling ~s with arguments ~e" name args ) ) ) > ``` The define-noisy binding provided by this module is a [macro](macros.html#%28tech._macro%29) that acts like [define](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=define.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._define%2529%2529&version=8.18.0.13) for a function, but it causes each call to the function to print the arguments that are provided to the function: > ```racket > > ( require ' noisy ) > > ( define-noisy ( f x y ) ( + x y ) ) > > ( f 1 2 ) > calling f with arguments '(1 2) > 3 > ``` Roughly, the define-noisy form works by replacing > ```racket > ( define-noisy ( f x y ) > ( + x y ) ) > ``` with > ```racket > ( define ( f x y ) > ( show-arguments ' f ( list x y ) ) > ( + x y ) ) > ``` Since show-arguments isn’t provided by the noisy module, however, this literal textual replacement is not quite right. The actual replacement correctly tracks the origin of identifiers like show-arguments, so they can refer to other definitions in the place where the macro is defined—even if those identifiers are not available at the place where the macro is used. There’s more to the macro and module interaction than identifier binding. The [define-syntax-rule](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=stx-patterns.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fmisc..rkt%2529._define-syntax-rule%2529%2529&version=8.18.0.13) form is itself a macro, and it expands to compile-time code that implements the transformation from define-noisy into [define](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=define.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._define%2529%2529&version=8.18.0.13). The module system keeps track of which code needs to run at compile and which needs to run normally, as explained more in [Compile and Run-Time Phases](stx-phases.html) and [Module Instantiations and Visits](macro-module.html). ------------------------------------------------------------------------ # 6.8 Protected Exports ### 6.8 Protected Exports Sometimes, a module needs to export bindings to other modules that are at the same trust level as the exporting module, while at the same time preventing access from untrusted modules. Such exports should use the [protect-out](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._protect-out%2529%2529&version=8.18.0.13) form in [provide](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._provide%2529%2529&version=8.18.0.13). For example, [ffi/unsafe](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=foreign&rel=index.html&version=8.18.0.13) exports all of its unsafe bindings as protected in this sense. Levels of trust are implemented with [code inspectors](code-inspectors_protect.html#%28tech._code._inspector%29) (see [Code Inspectors for Trusted and Untrusted Code](code-inspectors_protect.html)). Only modules loaded with an equally strong code inspector as an exporting module can use protected bindings from the exporting module. Operations like [dynamic-require](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Module_Names_and_Loading.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._dynamic-require%2529%2529&version=8.18.0.13) are granted access depending on the current code inspector as determined by [current-code-inspector](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=modprotect.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._current-code-inspector%2529%2529&version=8.18.0.13). When a module re-exports a protected binding, it does not need to use [protect-out](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._protect-out%2529%2529&version=8.18.0.13) again. Access is always determined by the code inspector of the module that originally defines a protected binding. When using a protected binding within a module, take care to either provide new bindings from the module with [protect-out](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._protect-out%2529%2529&version=8.18.0.13) or ensure that no provided bindings expose functionality that was meant to be protected in the first place. ------------------------------------------------------------------------ # 7 Contracts ## 7 Contracts This chapter provides a gentle introduction to Racket’s contract system. > > > <img src="magnify.png" width="24" height="24" alt="+" />[Contracts](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=contracts.html&version=8.18.0.13) in [The Racket Reference](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=index.html&version=8.18.0.13) provides more on contracts. | | |---------------------------------------------------------------------------------------------------------------------------------------------------------------------| |     [7.1 Contracts and Boundaries](contract-boundaries.html) | |       [7.1.1 Contract Violations](contract-boundaries.html#%28part._contracts-amount0%29) | |       [7.1.2 Experimenting with Contracts and Modules](contract-boundaries.html#%28part._.Experimenting_with_.Contracts_and_.Modules%29) | |       [7.1.3 Experimenting with Nested Contract Boundaries](contract-boundaries.html#%28part._contracts-intro-nested%29) | |     [7.2 Simple Contracts on Functions](contract-func.html) | |       [7.2.1 Styles of ->](contract-func.html#%28part._.Styles_of_-_%29) | |       [7.2.2 Using define/contract and ->](contract-func.html#%28part._simple-nested%29) | |       [7.2.3 any and any/c](contract-func.html#%28part._any_and_any_c%29) | |       [7.2.4 Rolling Your Own Contracts](contract-func.html#%28part._contracts-own%29) | |       [7.2.5 Contracts on Higher-order Functions](contract-func.html#%28part._.Contracts_on_.Higher-order_.Functions%29) | |       [7.2.6 Contract Messages with “???”](contract-func.html#%28part._contracts-flat-named-contracts%29) | |       [7.2.7 Dissecting a contract error message](contract-func.html#%28part._contracts-dissecting-contract-errors%29) | |     [7.3 Contracts on Functions in General](contracts-general-functions.html) | |       [7.3.1 Optional Arguments](contracts-general-functions.html#%28part._contracts-optional%29) | |       [7.3.2 Rest Arguments](contracts-general-functions.html#%28part._contracts-rest-args%29) | |       [7.3.3 Keyword Arguments](contracts-general-functions.html#%28part._contracts-keywords%29) | |       [7.3.4 Optional Keyword Arguments](contracts-general-functions.html#%28part._contracts-optional-keywords%29) | |       [7.3.5 Contracts for case-lambda](contracts-general-functions.html#%28part._contracts-case-lambda%29) | |       [7.3.6 Argument and Result Dependencies](contracts-general-functions.html#%28part._contracts-arrow-d%29) | |       [7.3.7 Checking State Changes](contracts-general-functions.html#%28part._contracts-arrow-d-eval-order%29) | |       [7.3.8 Multiple Result Values](contracts-general-functions.html#%28part._contracts-multiple%29) | |       [7.3.9 Fixed but Statically Unknown Arities](contracts-general-functions.html#%28part._contracts-no-domain%29) | |     [7.4 Contracts: A Thorough Example](contracts-first.html) | |     [7.5 Contracts on Structures](contracts-struct.html) | |       [7.5.1 Guarantees for a Specific Value](contracts-struct.html#%28part._contracts-single-struct%29) | |       [7.5.2 Guarantees for All Values](contracts-struct.html#%28part._contracts-define-struct%29) | |       [7.5.3 Checking Properties of Data Structures](contracts-struct.html#%28part._contracts-lazy-contracts%29) | |     [7.6 Abstract Contracts using #:exists and #:∃](contracts-exists.html) | |     [7.7 Additional Examples](contracts-examples.html) | |       [7.7.1 A Customer-Manager Component](contracts-examples.html#%28part._.A_.Customer-.Manager_.Component%29) | |       [7.7.2 A Parameteric (Simple) Stack](contracts-examples.html#%28part._.A_.Parameteric__.Simple__.Stack%29) | |       [7.7.3 A Dictionary](contracts-examples.html#%28part._.A_.Dictionary%29) | |       [7.7.4 A Queue](contracts-examples.html#%28part._.A_.Queue%29) | |     [7.8 Building New Contracts](Building_New_Contracts.html) | |       [7.8.1 Contract Struct Properties](Building_New_Contracts.html#%28part._.Contract_.Struct_.Properties%29) | |       [7.8.2 With all the Bells and Whistles](Building_New_Contracts.html#%28part._.With_all_the_.Bells_and_.Whistles%29) | |     [7.9 Gotchas](contracts-gotchas.html) | |       [7.9.1 Contracts and eq?](contracts-gotchas.html#%28part._.Contracts_and_eq_%29) | |       [7.9.2 Contract boundaries and define/contract](contracts-gotchas.html#%28part._contracts-gotcha-nested%29) | |       [7.9.3 Exists Contracts and Predicates](contracts-gotchas.html#%28part._contracts-exists-gotcha%29) | |       [7.9.4 Defining Recursive Contracts](contracts-gotchas.html#%28part._.Defining_.Recursive_.Contracts%29) | |       [7.9.5 Mixing set! and contract-out](contracts-gotchas.html#%28part._.Mixing_set__and_contract-out%29) | ------------------------------------------------------------------------ # 7.1 Contracts and Boundaries ### 7.1 Contracts and Boundaries 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. In this spirit, Racket encourages contracts mainly at module boundaries. Specifically, programmers may attach contracts to [provide](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._provide%2529%2529&version=8.18.0.13) clauses and thus impose constraints and promises on the use of exported values. For example, the export specification > ```racket > #lang racket > ( provide ( contract-out [ amount positive? ] ) ) > ( define amount ... ) > ``` 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: > ```racket > #lang racket/base > ( require racket/contract ) ; now we can write contracts > ( provide ( contract-out [ amount positive? ] ) ) > ( define amount ... ) > ``` #### 7.1.1 Contract Violations If we bind amount to a number that is not positive, > ```racket > #lang racket > ( provide ( contract-out [ amount 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: > ```racket > #lang racket > ( provide ( contract-out [ amount positive? ] ) ) > ( define amount ' amount ) > ``` In this case, the monitoring system will apply [positive?](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=number-types.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._positive%7E3f%2529%2529&version=8.18.0.13) to a symbol, but [positive?](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=number-types.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._positive%7E3f%2529%2529&version=8.18.0.13) 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](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=data-structure-contracts.html%23%2528def._%2528%2528lib._racket%252Fcontract%252Fbase..rkt%2529._and%252Fc%2529%2529&version=8.18.0.13): > ([provide](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._provide%2529%2529&version=8.18.0.13) ([contract-out](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=attaching-contracts-to-values.html%23%2528form._%2528%2528lib._racket%252Fcontract%252Fbase..rkt%2529._contract-out%2529%2529&version=8.18.0.13) \[amount ([and/c](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=data-structure-contracts.html%23%2528def._%2528%2528lib._racket%252Fcontract%252Fbase..rkt%2529._and%252Fc%2529%2529&version=8.18.0.13) [number?](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=number-types.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._number%7E3f%2529%2529&version=8.18.0.13) [positive?](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=number-types.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._positive%7E3f%2529%2529&version=8.18.0.13))\])) #### 7.1.2 Experimenting with Contracts and Modules All of the contracts and modules 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](intro.html#%28tech._definitions._area%29), use Racket’s submodules. For example, try the example earlier in this section like this: > ```racket > #lang racket > ( module+ server > ( provide ( contract-out [ amount ( and/c number? positive? ) ] ) ) > ( define amount 150 ) ) > ( module+ main > ( require ( submod ".." server ) ) > ( + amount 10 ) ) > ``` Each of the modules and their contracts are wrapped in parentheses with the [module+](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=module.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._module%252B%2529%2529&version=8.18.0.13) keyword at the front. The first form after [module](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=module.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._module%2529%2529&version=8.18.0.13) is the name of the module to be used in a subsequent [require](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._require%2529%2529&version=8.18.0.13) statement (where each reference through a [require](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._require%2529%2529&version=8.18.0.13) prefixes the name with ".."). #### 7.1.3 Experimenting with Nested Contract Boundaries In many cases, it makes sense to attach contracts at module boundaries. It is often convenient, however, to be able to use contracts at a finer granularity than modules. The [define/contract](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=attaching-contracts-to-values.html%23%2528form._%2528%2528lib._racket%252Fcontract%252Fregion..rkt%2529._define%252Fcontract%2529%2529&version=8.18.0.13) form enables this kind of use: > ```racket > #lang racket > ( define/contract amount > ( and/c number? positive? ) > 150 ) > ( + amount 10 ) > ``` In this example, the [define/contract](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=attaching-contracts-to-values.html%23%2528form._%2528%2528lib._racket%252Fcontract%252Fregion..rkt%2529._define%252Fcontract%2529%2529&version=8.18.0.13) form establishes a contract boundary between the definition of amount and its surrounding context. In other words, the two parties here are the definition and the module that contains it. Forms that create these nested contract boundaries can sometimes be subtle to use because they may have unexpected performance implications or blame a party that may seem unintuitive. These subtleties are explained in [Using define/contract and ->](contract-func.html#%28part._simple-nested%29) and [Contract boundaries and define/contract](contracts-gotchas.html#%28part._contracts-gotcha-nested%29). ------------------------------------------------------------------------ # 7.2 Simple Contracts on Functions ### 7.2 Simple Contracts on Functions A mathematical function has a domain and a range. The domain indicates the kind of values that the function can accept as arguments, and the range indicates the kind of values that it produces. The conventional notation for describing a function with its domain and range is > f : A [->](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=function-contracts.html%23%2528form._%2528%2528lib._racket%252Fcontract%252Fbase..rkt%2529._-%7E3e%2529%2529&version=8.18.0.13) B where A is the domain of the function and B is the range. Functions in a programming language have domains and ranges, too, and a contract can ensure that a function receives only values in its domain and produces only values in its range. A [->](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=function-contracts.html%23%2528form._%2528%2528lib._racket%252Fcontract%252Fbase..rkt%2529._-%7E3e%2529%2529&version=8.18.0.13) creates such a contract for a function. The forms after a [->](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=function-contracts.html%23%2528form._%2528%2528lib._racket%252Fcontract%252Fbase..rkt%2529._-%7E3e%2529%2529&version=8.18.0.13) specify contracts for the domains and finally a contract for the range. Here is a module that might represent a bank account: > ```racket > #lang racket > ( provide ( contract-out > [ deposit ( -> number? any ) ] > [ balance ( -> number? ) ] ) ) > ( define amount 0 ) > ( define ( deposit a ) ( set! amount ( + amount a ) ) ) > ( define ( balance ) amount ) > ``` The module exports two functions: - deposit, which accepts a number and returns some value that is not specified in the contract, and - balance, which returns a number indicating the current balance of the account. When a module exports a function, it establishes two channels of communication between itself as a “server” and the “client” module that imports the function. If the client module calls the function, it sends a value into the server module. Conversely, if such a function call ends and the function returns a value, the server module sends a value back to the client module. This client–server distinction is important, because when something goes wrong, one or the other of the parties is to blame. If a client module were to apply deposit to 'millions, it would violate the contract. The contract-monitoring system would catch this violation and blame the client for breaking the contract with the above module. In contrast, if the balance function were to return 'broke, the contract-monitoring system would blame the server module. A [->](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=function-contracts.html%23%2528form._%2528%2528lib._racket%252Fcontract%252Fbase..rkt%2529._-%7E3e%2529%2529&version=8.18.0.13) by itself is not a contract; it is a contract combinator, which combines other contracts to form a contract. #### 7.2.1 Styles of [->](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=function-contracts.html%23%2528form._%2528%2528lib._racket%252Fcontract%252Fbase..rkt%2529._-%7E3e%2529%2529&version=8.18.0.13) If you are used to mathematical functions, you may prefer a contract arrow to appear between the domain and the range of a function, not at the beginning. If you have read [How to Design Programs](https://htdp.org), you have seen this many times. Indeed, you may have seen contracts such as these in other people’s code: > ```racket > ( provide ( contract-out > [ deposit ( number? . -> . any ) ] ) ) > ``` If a Racket S-expression contains two dots with a symbol in the middle, the reader re-arranges the S-expression and place the symbol at the front, as described in [Lists and Racket Syntax](Pairs__Lists__and_Racket_Syntax.html#%28part._lists-and-syntax%29). Thus, > ([number?](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=number-types.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._number%7E3f%2529%2529&version=8.18.0.13) . [->](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=function-contracts.html%23%2528form._%2528%2528lib._racket%252Fcontract%252Fbase..rkt%2529._-%7E3e%2529%2529&version=8.18.0.13) . [any](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=data-structure-contracts.html%23%2528form._%2528%2528lib._racket%252Fcontract%252Fprivate%252Fmisc..rkt%2529._any%2529%2529&version=8.18.0.13)) is just another way of writing > ([->](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=function-contracts.html%23%2528form._%2528%2528lib._racket%252Fcontract%252Fbase..rkt%2529._-%7E3e%2529%2529&version=8.18.0.13) [number?](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=number-types.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._number%7E3f%2529%2529&version=8.18.0.13) [any](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=data-structure-contracts.html%23%2528form._%2528%2528lib._racket%252Fcontract%252Fprivate%252Fmisc..rkt%2529._any%2529%2529&version=8.18.0.13)) #### 7.2.2 Using [define/contract](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=attaching-contracts-to-values.html%23%2528form._%2528%2528lib._racket%252Fcontract%252Fregion..rkt%2529._define%252Fcontract%2529%2529&version=8.18.0.13) and [->](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=function-contracts.html%23%2528form._%2528%2528lib._racket%252Fcontract%252Fbase..rkt%2529._-%7E3e%2529%2529&version=8.18.0.13) The [define/contract](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=attaching-contracts-to-values.html%23%2528form._%2528%2528lib._racket%252Fcontract%252Fregion..rkt%2529._define%252Fcontract%2529%2529&version=8.18.0.13) form introduced in [Experimenting with Nested Contract Boundaries](contract-boundaries.html#%28part._contracts-intro-nested%29) can also be used to define functions that come with a contract. For example, > ```racket > ( define/contract ( deposit amount ) > ( -> number? any ) > ; implementation goes here > .... ) > ``` which defines the deposit function with the contract from earlier. Note that this has two potentially important impacts on the use of deposit: 1. The contract will be checked on any call to deposit that is outside of the definition of deposit – even those inside the module in which it is defined. Because there may be many calls inside the module, this checking may cause the contract to be checked too often, which could lead to a performance degradation. This is especially true if the function is called repeatedly from a loop. 2. In some situations, a function may be written to accept a more lax set of inputs when called by other code in the same module. For such use cases, the contract boundary established by [define/contract](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=attaching-contracts-to-values.html%23%2528form._%2528%2528lib._racket%252Fcontract%252Fregion..rkt%2529._define%252Fcontract%2529%2529&version=8.18.0.13) is too strict. #### 7.2.3 [any](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=data-structure-contracts.html%23%2528form._%2528%2528lib._racket%252Fcontract%252Fprivate%252Fmisc..rkt%2529._any%2529%2529&version=8.18.0.13) and [any/c](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=data-structure-contracts.html%23%2528def._%2528%2528lib._racket%252Fcontract%252Fprivate%252Fmisc..rkt%2529._any%252Fc%2529%2529&version=8.18.0.13) The [any](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=data-structure-contracts.html%23%2528form._%2528%2528lib._racket%252Fcontract%252Fprivate%252Fmisc..rkt%2529._any%2529%2529&version=8.18.0.13) contract used for deposit matches any kind of result, and it can only be used in the range position of a function contract. Instead of [any](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=data-structure-contracts.html%23%2528form._%2528%2528lib._racket%252Fcontract%252Fprivate%252Fmisc..rkt%2529._any%2529%2529&version=8.18.0.13) above, we could use the more specific contract [void?](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=void.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._void%7E3f%2529%2529&version=8.18.0.13), which says that the function will always return the ([void](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=void.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._void%2529%2529&version=8.18.0.13)) value. The [void?](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=void.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._void%7E3f%2529%2529&version=8.18.0.13) contract, however, would require the contract monitoring system to check the return value every time the function is called, even though the “client” module can’t do much with the value. In contrast, [any](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=data-structure-contracts.html%23%2528form._%2528%2528lib._racket%252Fcontract%252Fprivate%252Fmisc..rkt%2529._any%2529%2529&version=8.18.0.13) tells the monitoring system not to check the return value, it tells a potential client that the “server” module makes no promises at all about the function’s return value, even whether it is a single value or multiple values. The [any/c](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=data-structure-contracts.html%23%2528def._%2528%2528lib._racket%252Fcontract%252Fprivate%252Fmisc..rkt%2529._any%252Fc%2529%2529&version=8.18.0.13) contract is similar to [any](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=data-structure-contracts.html%23%2528form._%2528%2528lib._racket%252Fcontract%252Fprivate%252Fmisc..rkt%2529._any%2529%2529&version=8.18.0.13), in that it makes no demands on a value. Unlike [any](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=data-structure-contracts.html%23%2528form._%2528%2528lib._racket%252Fcontract%252Fprivate%252Fmisc..rkt%2529._any%2529%2529&version=8.18.0.13), [any/c](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=data-structure-contracts.html%23%2528def._%2528%2528lib._racket%252Fcontract%252Fprivate%252Fmisc..rkt%2529._any%252Fc%2529%2529&version=8.18.0.13) indicates a single value, and it is suitable for use as an argument contract. Using [any/c](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=data-structure-contracts.html%23%2528def._%2528%2528lib._racket%252Fcontract%252Fprivate%252Fmisc..rkt%2529._any%252Fc%2529%2529&version=8.18.0.13) as a range contract imposes a check that the function produces a single value. That is, > ([->](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=function-contracts.html%23%2528form._%2528%2528lib._racket%252Fcontract%252Fbase..rkt%2529._-%7E3e%2529%2529&version=8.18.0.13) [integer?](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=number-types.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._integer%7E3f%2529%2529&version=8.18.0.13) [any](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=data-structure-contracts.html%23%2528form._%2528%2528lib._racket%252Fcontract%252Fprivate%252Fmisc..rkt%2529._any%2529%2529&version=8.18.0.13)) describes a function that accepts an integer and returns any number of values, while > ([->](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=function-contracts.html%23%2528form._%2528%2528lib._racket%252Fcontract%252Fbase..rkt%2529._-%7E3e%2529%2529&version=8.18.0.13) [integer?](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=number-types.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._integer%7E3f%2529%2529&version=8.18.0.13) [any/c](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=data-structure-contracts.html%23%2528def._%2528%2528lib._racket%252Fcontract%252Fprivate%252Fmisc..rkt%2529._any%252Fc%2529%2529&version=8.18.0.13)) describes a function that accepts an integer and produces a single result (but does not say anything more about the result). The function > ([define](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=define.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._define%2529%2529&version=8.18.0.13) (f x) ([values](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=values.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._values%2529%2529&version=8.18.0.13) ([+](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=generic-numbers.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._%252B%2529%2529&version=8.18.0.13) x 1) ([-](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=generic-numbers.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._-%2529%2529&version=8.18.0.13) x 1))) matches ([->](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=function-contracts.html%23%2528form._%2528%2528lib._racket%252Fcontract%252Fbase..rkt%2529._-%7E3e%2529%2529&version=8.18.0.13) [integer?](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=number-types.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._integer%7E3f%2529%2529&version=8.18.0.13) [any](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=data-structure-contracts.html%23%2528form._%2528%2528lib._racket%252Fcontract%252Fprivate%252Fmisc..rkt%2529._any%2529%2529&version=8.18.0.13)), but not ([->](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=function-contracts.html%23%2528form._%2528%2528lib._racket%252Fcontract%252Fbase..rkt%2529._-%7E3e%2529%2529&version=8.18.0.13) [integer?](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=number-types.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._integer%7E3f%2529%2529&version=8.18.0.13) [any/c](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=data-structure-contracts.html%23%2528def._%2528%2528lib._racket%252Fcontract%252Fprivate%252Fmisc..rkt%2529._any%252Fc%2529%2529&version=8.18.0.13)). Use [any/c](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=data-structure-contracts.html%23%2528def._%2528%2528lib._racket%252Fcontract%252Fprivate%252Fmisc..rkt%2529._any%252Fc%2529%2529&version=8.18.0.13) as a result contract when it is particularly important to promise a single result from a function. Use [any](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=data-structure-contracts.html%23%2528form._%2528%2528lib._racket%252Fcontract%252Fprivate%252Fmisc..rkt%2529._any%2529%2529&version=8.18.0.13) when you want to promise as little as possible (and incur as little checking as possible) for a function’s result. #### 7.2.4 Rolling Your Own Contracts The deposit function adds the given number to the value of amount. While the function’s contract prevents clients from applying it to non-numbers, the contract still allows them to apply the function to complex numbers, negative numbers, or inexact numbers, none of which sensibly represent amounts of money. The contract system allows programmers to define their own contracts as functions: > ```racket > #lang racket > ( define ( amount? a ) > ( and ( number? a ) ( integer? a ) ( exact? a ) ( >= a 0 ) ) ) > ( provide ( contract-out > ; an amount is a natural number of cents > ; is the given number an amount? > [ deposit ( -> amount? any ) ] > [ amount? ( -> any/c boolean? ) ] > [ balance ( -> amount? ) ] ) ) > ( define amount 0 ) > ( define ( deposit a ) ( set! amount ( + amount a ) ) ) > ( define ( balance ) amount ) > ``` This module defines an amount? function and uses it as a contract within [->](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=function-contracts.html%23%2528form._%2528%2528lib._racket%252Fcontract%252Fbase..rkt%2529._-%7E3e%2529%2529&version=8.18.0.13) contracts. When a client calls the deposit function as exported with the contract ([->](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=function-contracts.html%23%2528form._%2528%2528lib._racket%252Fcontract%252Fbase..rkt%2529._-%7E3e%2529%2529&version=8.18.0.13) amount? [any](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=data-structure-contracts.html%23%2528form._%2528%2528lib._racket%252Fcontract%252Fprivate%252Fmisc..rkt%2529._any%2529%2529&version=8.18.0.13)), it must supply an exact, nonnegative integer, otherwise the amount? function applied to the argument will return #f, which will cause the contract-monitoring system to blame the client. Similarly, the server module must provide an exact, nonnegative integer as the result of balance to remain blameless. Of course, it makes no sense to restrict a channel of communication to values that the client doesn’t understand. Therefore the module also exports the amount? predicate itself, with a contract saying that it accepts an arbitrary value and returns a boolean. In this case, we could also have used [natural-number/c](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=data-structure-contracts.html%23%2528def._%2528%2528lib._racket%252Fcontract%252Fprivate%252Fmisc..rkt%2529._natural-number%252Fc%2529%2529&version=8.18.0.13) in place of amount?, since it implies exactly the same check: > ```racket > ( provide ( contract-out > [ deposit ( -> natural-number/c any ) ] > [ balance ( -> natural-number/c ) ] ) ) > ``` Every function that accepts one argument can be treated as a predicate and thus used as a contract. For combining existing checks into a new one, however, contract combinators such as [and/c](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=data-structure-contracts.html%23%2528def._%2528%2528lib._racket%252Fcontract%252Fbase..rkt%2529._and%252Fc%2529%2529&version=8.18.0.13) and [or/c](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=data-structure-contracts.html%23%2528def._%2528%2528lib._racket%252Fcontract%252Fbase..rkt%2529._or%252Fc%2529%2529&version=8.18.0.13) are often useful. For example, here is yet another way to write the contracts above: > ```racket > ( define amount/c > ( and/c number? integer? exact? ( or/c positive? zero? ) ) ) > ( provide ( contract-out > [ deposit ( -> amount/c any ) ] > [ balance ( -> amount/c ) ] ) ) > ``` Other values also serve double duty as contracts. For example, if a function accepts a number or #f, ([or/c](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=data-structure-contracts.html%23%2528def._%2528%2528lib._racket%252Fcontract%252Fbase..rkt%2529._or%252Fc%2529%2529&version=8.18.0.13) [number?](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=number-types.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._number%7E3f%2529%2529&version=8.18.0.13) #f) suffices. Similarly, the amount/c contract could have been written with a 0 in place of [zero?](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=number-types.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._zero%7E3f%2529%2529&version=8.18.0.13). If you use a regular expression as a contract, the contract accepts strings and byte strings that match the regular expression. Naturally, you can mix your own contract-implementing functions with combinators like [and/c](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=data-structure-contracts.html%23%2528def._%2528%2528lib._racket%252Fcontract%252Fbase..rkt%2529._and%252Fc%2529%2529&version=8.18.0.13). Here is a module for creating strings from banking records: > ```racket > #lang racket > ( define ( has-decimal? str ) > ( define L ( string-length str ) ) > ( and ( >= L 3 ) > ( char=? #\. ( string-ref str ( - L 3 ) ) ) ) ) > ( provide ( contract-out > ; convert a random number to a string > [ format-number ( -> number? string? ) ] > ; convert an amount into a string with a decimal > ; point, as in an amount of US currency > [ format-nat ( -> natural-number/c > ( and/c string? has-decimal? ) ) ] ) ) > ``` The contract of the exported function format-number specifies that the function consumes a number and produces a string. The contract of the exported function format-nat is more interesting than the one of format-number. It consumes only natural numbers. Its range contract promises a string that has a . in the third position from the right. If we want to strengthen the promise of the range contract for format-nat so that it admits only strings with digits and a single dot, we could write it like this: > ```racket > #lang racket > ( define ( digit-char? x ) > ( member x ' ( #\1 #\2 #\3 #\4 #\5 #\6 #\7 #\8 #\9 #\0 ) ) ) > ( define ( has-decimal? str ) > ( define L ( string-length str ) ) > ( and ( >= L 3 ) > ( char=? #\. ( string-ref str ( - L 3 ) ) ) ) ) > ( define ( is-decimal-string? str ) > ( define L ( string-length str ) ) > ( and ( has-decimal? str ) > ( andmap digit-char? > ( string->list ( substring str 0 ( - L 3 ) ) ) ) > ( andmap digit-char? > ( string->list ( substring str ( - L 2 ) L ) ) ) ) ) > .... > ( provide ( contract-out > .... > ; convert an amount (natural number) of cents > ; into a dollar-based string > [ format-nat ( -> natural-number/c > ( and/c string? > is-decimal-string? ) ) ] ) ) > ``` Alternately, in this case, we could use a regular expression as a contract: > ```racket > #lang racket > ( provide > ( contract-out > .... > ; convert an amount (natural number) of cents > ; into a dollar-based string > [ format-nat ( -> natural-number/c > ( and/c string? #rx"[0-9]*\\.[0-9][0-9]" ) ) ] ) ) > ``` #### 7.2.5 Contracts on Higher-order Functions Function contracts are not just restricted to having simple predicates on their domains or ranges. Any of the contract combinators discussed here, including function contracts themselves, can be used as contracts on the arguments and results of a function. For example, > ([->](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=function-contracts.html%23%2528form._%2528%2528lib._racket%252Fcontract%252Fbase..rkt%2529._-%7E3e%2529%2529&version=8.18.0.13) [integer?](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=number-types.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._integer%7E3f%2529%2529&version=8.18.0.13) ([->](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=function-contracts.html%23%2528form._%2528%2528lib._racket%252Fcontract%252Fbase..rkt%2529._-%7E3e%2529%2529&version=8.18.0.13) [integer?](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=number-types.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._integer%7E3f%2529%2529&version=8.18.0.13) [integer?](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=number-types.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._integer%7E3f%2529%2529&version=8.18.0.13))) is a contract that describes a curried function. It matches functions that accept one argument and then return another function accepting a second argument before finally returning an integer. If a server exports a function make-adder with this contract, and if make-adder returns a value other than a function, then the server is to blame. If make-adder does return a function, but the resulting function is applied to a value other than an integer, then the client is to blame. Similarly, the contract > ([->](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=function-contracts.html%23%2528form._%2528%2528lib._racket%252Fcontract%252Fbase..rkt%2529._-%7E3e%2529%2529&version=8.18.0.13) ([->](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=function-contracts.html%23%2528form._%2528%2528lib._racket%252Fcontract%252Fbase..rkt%2529._-%7E3e%2529%2529&version=8.18.0.13) [integer?](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=number-types.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._integer%7E3f%2529%2529&version=8.18.0.13) [integer?](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=number-types.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._integer%7E3f%2529%2529&version=8.18.0.13)) [integer?](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=number-types.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._integer%7E3f%2529%2529&version=8.18.0.13)) describes functions that accept other functions as its input. If a server exports a function twice with this contract and the twice is applied to a value other than a function of one argument, then the client is to blame. If twice is applied to a function of one argument and twice calls the given function on a value other than an integer, then the server is to blame. #### 7.2.6 Contract Messages with “???” You wrote your module. You added contracts. You put them into the interface so that client programmers have all the information from interfaces. It’s a piece of art: > ```racket > > ( module bank-server racket ( provide ( contract-out [ deposit ( -> ( λ ( x ) ( and ( number? x ) ( integer? x ) ( >= x 0 ) ) ) any ) ] ) ) ( define total 0 ) ( define ( deposit a ) ( set! total ( + a total ) ) ) ) > ``` Several clients used your module. Others used their modules in turn. And all of a sudden one of them sees this error message: > ```racket > > ( require ' bank-server ) > > ( deposit -1 0 ) > deposit: contract violation > expected: ??? > given: -10 > in: the 1st argument of > (-> ??? any) > contract from: bank-server > blaming: top-level > (assuming the contract is correct) > at: eval:2:0 > ``` What is the ??? doing there? Wouldn’t it be nice if we had a name for this class of data much like we have string, number, and so on? For this situation, Racket provides flat named contracts. The use of “contract” in this term shows that contracts are first-class values. The “flat” means that the collection of data is a subset of the built-in atomic classes of data; they are described by a predicate that consumes all Racket values and produces a boolean. The “named” part says what we want to do, which is to name the contract so that error messages become intelligible: > ```racket > > ( module improved-bank-server racket ( provide ( contract-out [ deposit ( -> ( flat-named-contract ' amount ( λ ( x ) ( and ( number? x ) ( integer? x ) ( >= x 0 ) ) ) ) any ) ] ) ) ( define total 0 ) ( define ( deposit a ) ( set! total ( + a total ) ) ) ) > ``` With this little change, the error message becomes quite readable: > ```racket > > ( require ' improved-bank-server ) > > ( deposit -1 0 ) > deposit: contract violation > expected: amount > given: -10 > in: the 1st argument of > (-> amount any) > contract from: improved-bank-server > blaming: top-level > (assuming the contract is correct) > at: eval:5:0 > ``` #### 7.2.7 Dissecting a contract error message In general, each contract error message consists of six sections: - a name for the function or method associated with the contract and either the phrase “contract violation” or “broke its contract” depending on whether the contract was violated by the client or the server; e.g. in the previous example: | | |-----------------------------| | deposit: contract violation | - a description of the precise aspect of the contract that was violated, | | |------------------| | expected: amount | | given: -10 | - the complete contract plus a path into it showing which aspect was violated, | | |-------------------------| | in: the 1st argument of | | (-> amount any) | - the module where the contract was put (or, more generally, the boundary that the contract mediates), | | |-------------------------------------| | contract from: improved-bank-server | - who was blamed, | | |------------------------------------| | blaming: top-level | | (assuming the contract is correct) | - and the source location where the contract appears. | | |--------------| | at: eval:5:0 | ------------------------------------------------------------------------ # 7.3 Contracts on Functions in General ### 7.3 Contracts on Functions in General The [->](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=function-contracts.html%23%2528form._%2528%2528lib._racket%252Fcontract%252Fbase..rkt%2529._-%7E3e%2529%2529&version=8.18.0.13) 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 [->*](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=function-contracts.html%23%2528form._%2528%2528lib._racket%252Fcontract%252Fbase..rkt%2529._-%7E3e%252A%2529%2529&version=8.18.0.13) and [->i](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=function-contracts.html%23%2528form._%2528%2528lib._racket%252Fcontract%252Fbase..rkt%2529._-%7E3ei%2529%2529&version=8.18.0.13). #### 7.3.1 Optional Arguments Take a look at this excerpt from a string-processing module: > ```racket > #lang racket > ( provide > ( contract-out > ; pad the given str left and right with > ; the (optional) char so that it is centered > [ string-pad-center ( -> * ( string? natural-number/c ) > ( char? ) > string? ) ] ) ) > ( define ( string-pad-center str width [ pad #\space ] ) > ( define field-width ( min width ( string-length str ) ) ) > ( define rmargin ( ceiling ( / ( - width field-width ) 2 ) ) ) > ( define lmargin ( floor ( / ( - width field-width ) 2 ) ) ) > ( string-append ( build-string lmargin ( λ ( x ) pad ) ) > str > ( build-string rmargin ( λ ( x ) pad ) ) ) ) > ``` 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 [->*](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=function-contracts.html%23%2528form._%2528%2528lib._racket%252Fcontract%252Fbase..rkt%2529._-%7E3e%252A%2529%2529&version=8.18.0.13), 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?](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=strings.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._string%7E3f%2529%2529&version=8.18.0.13) and [natural-number/c](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=data-structure-contracts.html%23%2528def._%2528%2528lib._racket%252Fcontract%252Fprivate%252Fmisc..rkt%2529._natural-number%252Fc%2529%2529&version=8.18.0.13). - The second one is a parenthesized group of contracts for all optional arguments: [char?](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=characters.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._char%7E3f%2529%2529&version=8.18.0.13). - 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. #### 7.3.2 Rest Arguments The [max](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=generic-numbers.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._max%2529%2529&version=8.18.0.13) 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](lambda.html#%28tech._rest._argument%29), such as in max-abs: > > > See [Declaring a Rest Argument](lambda.html#%28part._rest-args%29) for an introduction to rest arguments. > ```racket > ( define ( max-abs n . rst ) > ( foldr ( lambda ( n m ) ( max ( abs n ) m ) ) ( abs n ) rst ) ) > ``` To describe this function through a contract, you can use the [...](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=stx-patterns.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fstxcase-scheme..rkt%2529._......%2529%2529&version=8.18.0.13) feature of [->](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=function-contracts.html%23%2528form._%2528%2528lib._racket%252Fcontract%252Fbase..rkt%2529._-%7E3e%2529%2529&version=8.18.0.13). > ```racket > ( provide > ( contract-out > [ max-abs ( -> real? real? ... real? ) ] ) ) > ``` Alternatively, you can use [->*](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=function-contracts.html%23%2528form._%2528%2528lib._racket%252Fcontract%252Fbase..rkt%2529._-%7E3e%252A%2529%2529&version=8.18.0.13) with a #:rest keyword, which specifies a contract on a list of arguments after the required and optional arguments: > ```racket > ( provide > ( contract-out > [ max-abs ( -> * ( real? ) ( ) #:rest ( listof real? ) real? ) ] ) ) > ``` As always for [->*](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=function-contracts.html%23%2528form._%2528%2528lib._racket%252Fcontract%252Fbase..rkt%2529._-%7E3e%252A%2529%2529&version=8.18.0.13), 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](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=data-structure-contracts.html%23%2528def._%2528%2528lib._racket%252Fcontract%252Fbase..rkt%2529._listof%2529%2529&version=8.18.0.13) [real?](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=number-types.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._real%7E3f%2529%2529&version=8.18.0.13)). #### 7.3.3 Keyword Arguments It turns out that the [->](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=function-contracts.html%23%2528form._%2528%2528lib._racket%252Fcontract%252Fbase..rkt%2529._-%7E3e%2529%2529&version=8.18.0.13) 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](lambda.html#%28part._lambda-keywords%29) for an introduction to keyword arguments. > ```racket > #lang racket/gui > ( define ( ask-yes-or-no-question question > #:default answer > #:title title > #:width w > #:height h ) > ( define d ( new dialog% [ label title ] [ width w ] [ height h ] ) ) > ( define msg ( new message% [ label question ] [ parent d ] ) ) > ( define ( yes ) ( set! answer #t ) ( send d show #f ) ) > ( define ( no ) ( set! answer #f ) ( send d show #f ) ) > ( define yes-b ( new button% > [ label "Yes" ] [ parent d ] > [ callback ( λ ( x y ) ( yes ) ) ] > [ style ( if answer ' ( border ) ' ( ) ) ] ) ) > ( define no-b ( new button% > [ label "No" ] [ parent d ] > [ callback ( λ ( x y ) ( no ) ) ] > [ style ( if answer ' ( ) ' ( border ) ) ] ) ) > ( send d show #t ) > answer ) > ( provide ( contract-out > [ ask-yes-or-no-question > ( -> string? > #:default boolean? > #:title string? > #:width exact-integer? > #:height exact-integer? > boolean? ) ] ) ) > ``` > > > If you really want to ask a yes-or-no question via a GUI, you should use [message-box/custom](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=gui&rel=Windowing_Functions.html%23%2528def._%2528%2528lib._mred%252Fmain..rkt%2529._message-box%252Fcustom%2529%2529&version=8.18.0.13). 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 [->](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=function-contracts.html%23%2528form._%2528%2528lib._racket%252Fcontract%252Fbase..rkt%2529._-%7E3e%2529%2529&version=8.18.0.13), and in the same way that [lambda](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=lambda.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._lambda%2529%2529&version=8.18.0.13) (or [define](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=define.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._define%2529%2529&version=8.18.0.13)-based functions) allows a keyword to precede a functions formal argument, [->](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=function-contracts.html%23%2528form._%2528%2528lib._racket%252Fcontract%252Fbase..rkt%2529._-%7E3e%2529%2529&version=8.18.0.13) 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 [->](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=function-contracts.html%23%2528form._%2528%2528lib._racket%252Fcontract%252Fbase..rkt%2529._-%7E3e%2529%2529&version=8.18.0.13) relative to each other does not matter for clients of the function; only the relative order of argument contracts without keywords matters. #### 7.3.4 Optional Keyword Arguments Of course, many of the parameters in ask-yes-or-no-question (from the previous question) have reasonable defaults and should be made optional: > ```racket > ( define ( ask-yes-or-no-question question > #:default answer > #:title [ title "Yes or No?" ] > #:width [ w 400 ] > #:height [ h 200 ] ) > ... ) > ``` To specify this function’s contract, we need to use [->*](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=function-contracts.html%23%2528form._%2528%2528lib._racket%252Fcontract%252Fbase..rkt%2529._-%7E3e%252A%2529%2529&version=8.18.0.13) 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: > ```racket > ( provide ( contract-out > [ ask-yes-or-no-question > ( -> * ( string? > #:default boolean? ) > ( #:title string? > #:width exact-integer? > #:height exact-integer? ) > boolean? ) ] ) ) > ``` That is, we put the mandatory keywords in the first section, and we put the optional ones in the second section. #### 7.3.5 Contracts for [case-lambda](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=lambda.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._case-lambda%2529%2529&version=8.18.0.13) A function defined with [case-lambda](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=lambda.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._case-lambda%2529%2529&version=8.18.0.13) 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](lambda.html#%28part._case-lambda%29) for an introduction to [case-lambda](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=lambda.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._case-lambda%2529%2529&version=8.18.0.13). > ``` (define report-cost > ( case-lambda > [ ( lo hi ) ( format "between $~a and $~a" lo hi ) ] > [ ( desc ) ( format "~a of dollars" desc ) ] ) )   > ( report-cost 5 8 ) > "between $5 and $8" > > ( report-cost "millions" ) > "millions of dollars" ```
### 5.5 Structure Comparisons (x) → (-> provide (contract-out [ report-cost (case → (integer? integer? . → . string?) (string? . → . string?)) ]))``` ------------------------------------------------------------------------
# 7.9 Gotchas
### 7.9 Gotchas
#### 7.9.1 Contracts and [eq?](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Equality.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._eq%7E3f%2529%2529&version=8.18.0.13) As a general rule, adding a contract to a program should either leave the behavior of the program unchanged, or should signal a contract violation. And this is almost true for Racket contracts, with one exception: [eq?](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Equality.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._eq%7E3f%2529%2529&version=8.18.0.13). The [eq?](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Equality.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._eq%7E3f%2529%2529&version=8.18.0.13) procedure is designed to be fast and does not provide much in the way of guarantees, except that if it returns true, it means that the two values behave identically in all respects. Internally, this is implemented as pointer equality at a low-level so it exposes information about how Racket is implemented (and how contracts are implemented).
# 7.9 Gotchas Contracts interact poorly with [eq?](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Equality.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._eq%7E3f%2529%2529&version=8.18.0.13) because function contract checking is implemented internally as wrapper functions. For example, consider this module: > ```racket > #lang racket > ( define ( make-adder x ) > ( if ( = 1 x ) > add1 > ( lambda ( y ) ( + x y ) ) ) ) > ( provide ( contract-out > [ make-adder ( -> number? ( -> number? number? ) ) ] ) ) > ``` It exports the make-adder function that is the usual curried addition function, except that it returns Racket’s [add1](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=generic-numbers.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._add1%2529%2529&version=8.18.0.13) when its input is 1. You might expect that > ```racket > ( eq? ( make-adder 1 ) > ( make-adder 1 ) ) > ```
# 7.9 Gotchas would return #t, but it does not. If the contract were changed to [any/c](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=data-structure-contracts.html%23%2528def._%2528%2528lib._racket%252Fcontract%252Fprivate%252Fmisc..rkt%2529._any%252Fc%2529%2529&version=8.18.0.13) (or even ([->](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=function-contracts.html%23%2528form._%2528%2528lib._racket%252Fcontract%252Fbase..rkt%2529._-%7E3e%2529%2529&version=8.18.0.13) [number?](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=number-types.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._number%7E3f%2529%2529&version=8.18.0.13) [any/c](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=data-structure-contracts.html%23%2528def._%2528%2528lib._racket%252Fcontract%252Fprivate%252Fmisc..rkt%2529._any%252Fc%2529%2529&version=8.18.0.13))), then the [eq?](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Equality.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._eq%7E3f%2529%2529&version=8.18.0.13) call would return #t.
# 7.9 Gotchas Moral: Do not use [eq?](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Equality.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._eq%7E3f%2529%2529&version=8.18.0.13) on values that have contracts.
#### 7.9.2 Contract boundaries and [define/contract](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=attaching-contracts-to-values.html%23%2528form._%2528%2528lib._racket%252Fcontract%252Fregion..rkt%2529._define%252Fcontract%2529%2529&version=8.18.0.13) The contract boundaries established by [define/contract](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=attaching-contracts-to-values.html%23%2528form._%2528%2528lib._racket%252Fcontract%252Fregion..rkt%2529._define%252Fcontract%2529%2529&version=8.18.0.13), which creates a nested contract boundary, are sometimes unintuitive. This is especially true when multiple functions or other values with contracts interact. For example, consider these two interacting functions: > ```racket > > ( define/contract ( f x ) ( -> integer? integer? ) x ) > > ( define/contract ( g ) ( -> string? ) ( f "not an integer" ) ) > > ( g ) > f: contract violation > expected: integer? > given: "not an integer" > in: the 1st argument of > (-> integer? integer?) > contract from: (function f) > blaming: top-level > (assuming the contract is correct) > at: eval:2:0 > ``` One might expect that the function g will be blamed for breaking the terms of its contract with f. Blaming g would be right if f and g were directly establishing contracts with each other. They aren’t, however. Instead, the access between f and g is mediated through the top-level of the enclosing module.
# 7.9 Gotchas More precisely, f and the top-level of the module have the ([->](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=function-contracts.html%23%2528form._%2528%2528lib._racket%252Fcontract%252Fbase..rkt%2529._-%7E3e%2529%2529&version=8.18.0.13) [integer?](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=number-types.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._integer%7E3f%2529%2529&version=8.18.0.13) [integer?](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=number-types.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._integer%7E3f%2529%2529&version=8.18.0.13)) contract mediating their interaction; g and the top-level have ([->](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=function-contracts.html%23%2528form._%2528%2528lib._racket%252Fcontract%252Fbase..rkt%2529._-%7E3e%2529%2529&version=8.18.0.13) [string?](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=strings.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._string%7E3f%2529%2529&version=8.18.0.13)) mediating their interaction, but there is no contract directly between f and g. This means that the reference to f in the body of g is really the top-level of the module’s responsibility, not g’s. In other words, the function f has been given to g with no contract between g and the top-level and thus the top-level is blamed.
# 7.9 Gotchas If we wanted to add a contract between g and the top-level, we can use [define/contract](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=attaching-contracts-to-values.html%23%2528form._%2528%2528lib._racket%252Fcontract%252Fregion..rkt%2529._define%252Fcontract%2529%2529&version=8.18.0.13)’s #:freevar declaration and see the expected blame: > ```racket > > ( define/contract ( f x ) ( -> integer? integer? ) x ) > > ( define/contract ( g ) ( -> string? ) #:freevar f ( -> integer? integer? ) ( f "not an integer" ) ) > > ( g ) > f: contract violation > expected: integer? > given: "not an integer" > in: the 1st argument of > (-> integer? integer?) > contract from: top-level > blaming: (function g) > (assuming the contract is correct) > at: eval:6:0 > ``` Moral: if two values with contracts should interact, put them in separate modules with contracts at the module boundary or use #:freevar.
#### 7.9.3 Exists Contracts and Predicates Much like the [eq?](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Equality.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._eq%7E3f%2529%2529&version=8.18.0.13) example above, #:∃ contracts can change the behavior of a program. Specifically, the [null?](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=pairs.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._null%7E3f%2529%2529&version=8.18.0.13) predicate (and many other predicates) return #f for #:∃ contracts, and changing one of those contracts to [any/c](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=data-structure-contracts.html%23%2528def._%2528%2528lib._racket%252Fcontract%252Fprivate%252Fmisc..rkt%2529._any%252Fc%2529%2529&version=8.18.0.13) means that [null?](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=pairs.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._null%7E3f%2529%2529&version=8.18.0.13) might now return #t instead, resulting in arbitrarily different behavior depending on how this boolean might flow around in the program. Moral: Do not use predicates on #:∃ contracts.
#### 7.9.4 Defining Recursive Contracts When defining a self-referential contract, it is natural to use [define](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=define.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._define%2529%2529&version=8.18.0.13). For example, one might try to write a contract on streams like this: > ```racket > > ( define stream/c ( promise/c ( or/c null? ( cons/c number? stream/c ) ) ) ) > stream/c: undefined; > cannot reference an identifier before its definition > in module: top-level > ``` Unfortunately, this does not work because the value of stream/c is needed before it is defined. Put another way, all of the combinators evaluate their arguments eagerly, even though the values that they accept do not. Instead, use > ```racket > ( define stream/c > ( promise/c > ( or/c > null? > ( cons/c number? ( recursive-contract stream/c ) ) ) ) ) > ``` The use of [recursive-contract](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=contract-utilities.html%23%2528form._%2528%2528lib._racket%252Fcontract%252Fprivate%252Fbase..rkt%2529._recursive-contract%2529%2529&version=8.18.0.13) delays the evaluation of the identifier stream/c until after the contract is first checked, long enough to ensure that stream/c is defined. See also [Checking Properties of Data Structures](contracts-struct.html#%28part._contracts-lazy-contracts%29).
#### 7.9.5 Mixing [set!](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=set_.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._set%2521%2529%2529&version=8.18.0.13) and [contract-out](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=attaching-contracts-to-values.html%23%2528form._%2528%2528lib._racket%252Fcontract%252Fbase..rkt%2529._contract-out%2529%2529&version=8.18.0.13) The contract library assumes that variables exported via [contract-out](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=attaching-contracts-to-values.html%23%2528form._%2528%2528lib._racket%252Fcontract%252Fbase..rkt%2529._contract-out%2529%2529&version=8.18.0.13) are not assigned to, but does not enforce it. Accordingly, if you try to [set!](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=set_.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._set%2521%2529%2529&version=8.18.0.13) those variables, you may be surprised. Consider the following example: > ```racket > > ( module server racket ( define ( inc-x! ) ( set! x ( + x 1 ) ) ) ( define x 0 ) ( provide ( contract-out [ inc-x! ( -> void? ) ] [ x integer? ] ) ) ) > > ( module client racket ( require ' server ) ( define ( print-latest ) ( printf "x is ~s\n" x ) ) ( print-latest ) ( inc-x! ) ( print-latest ) ) > > ( require ' client ) > x is 0 x is 0 > ```
# 7.9 Gotchas Both calls to print-latest print 0, even though the value of x has been incremented (and the change is visible inside the module x). To work around this, export accessor functions, rather than exporting the variable directly, like this: > ```racket > #lang racket > ( define ( get-x ) x ) > ( define ( inc-x! ) ( set! x ( + x 1 ) ) ) > ( define x 0 ) > ( provide ( contract-out [ inc-x! ( -> void? ) ] > [ get-x ( -> integer? ) ] ) ) > ``` Moral: This is a bug that we will address in a future release. ------------------------------------------------------------------------
# 8 Input and Output
## 8 Input and Output > > > A Racket port corresponds to the Unix notion of a stream (not to be confused with [racket/stream](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=streams.html&version=8.18.0.13)’s streams). A Racket port represents a source or sink of data, such as a file, a terminal, a TCP connection, or an in-memory string. Ports provide sequential access in which data can be read or written a piece at a time, without requiring the data to be consumed or produced all at once. More specifically, an input port represents a source from which a program can read data, and an output port represents a sink to which a program can write data. | | |---------------------------------------------------------------------------------------| |     [8.1 Varieties of Ports](ports.html) | |     [8.2 Default Ports](default-ports.html) | |     [8.3 Reading and Writing Racket Data](read-write.html) | |     [8.4 Datatypes and Serialization](serialization.html) | |     [8.5 Bytes, Characters, and Encodings](encodings.html) | |     [8.6 I/O Patterns](io-patterns.html) | ------------------------------------------------------------------------
# 8.1 Varieties of Ports
### 8.1 Varieties of Ports Various functions create various kinds of ports. Here are a few examples: - Files: The [open-output-file](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=file-ports.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._open-output-file%2529%2529&version=8.18.0.13) function opens a file for writing, and [open-input-file](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=file-ports.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._open-input-file%2529%2529&version=8.18.0.13) opens a file for reading. Examples: > ```racket > > ( define out ( open-output-file "data" ) ) > > ( display "hello" out ) > > ( close-output-port out ) > > ( define in ( open-input-file "data" ) ) > > ( read-line in ) > "hello" > > ( close-input-port in ) > ``` If a file exists already, then [open-output-file](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=file-ports.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._open-output-file%2529%2529&version=8.18.0.13) raises an exception by default. Supply an option like #:exists 'truncate or #:exists 'update to re-write or update the file: Examples: > ```racket > > ( define out ( open-output-file "data" #:exists ' truncate ) ) > > ( display "howdy" out ) > > ( close-output-port out ) > ```
# 8.1 Varieties of Ports Instead of having to match the open calls with close calls, most Racket programmers will use the [call-with-input-file](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=file-ports.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._call-with-input-file%2529%2529&version=8.18.0.13) and [call-with-output-file](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=file-ports.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._call-with-output-file%2529%2529&version=8.18.0.13) functions which take a function to call to carry out the desired operation. This function gets as its only argument the port, which is automatically opened and closed for the operation. Examples: > ```racket > > ( call-with-output-file "data" #:exists ' truncate ( lambda ( out ) ( display "hello" out ) ) ) > > ( call-with-input-file "data" ( lambda ( in ) ( read-line in ) ) ) > "hello" > ```
# 8.1 Varieties of Ports - Strings: The [open-output-string](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=stringport.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._open-output-string%2529%2529&version=8.18.0.13) function creates a port that accumulates data into a string, and [get-output-string](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=stringport.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._get-output-string%2529%2529&version=8.18.0.13) extracts the accumulated string. The [open-input-string](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=stringport.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._open-input-string%2529%2529&version=8.18.0.13) function creates a port to read from a string. Examples: > ```racket > > ( define p ( open-output-string ) ) > > ( display "hello" p ) > > ( get-output-string p ) > "hello" > > ( read-line ( open-input-string "goodbye\nfarewell" ) ) > "goodbye" > ```
# 8.1 Varieties of Ports - TCP Connections: The [tcp-connect](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=tcp.html%23%2528def._%2528%2528lib._racket%252Ftcp..rkt%2529._tcp-connect%2529%2529&version=8.18.0.13) function creates both an input port and an output port for the client side of a TCP communication. The [tcp-listen](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=tcp.html%23%2528def._%2528%2528lib._racket%252Ftcp..rkt%2529._tcp-listen%2529%2529&version=8.18.0.13) function creates a server, which accepts connections via [tcp-accept](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=tcp.html%23%2528def._%2528%2528lib._racket%252Ftcp..rkt%2529._tcp-accept%2529%2529&version=8.18.0.13). Examples: > ```racket > > ( define server ( tcp-listen 12345 ) ) > > ( define-values ( c-in c-out ) ( tcp-connect "localhost" 12345 ) ) > > ( define-values ( s-in s-out ) ( tcp-accept server ) ) > > ( display "hello\n" c-out ) > > ( close-output-port c-out ) > > ( read-line s-in ) > "hello" > > ( read-line s-in ) > #<eof> > ```
# 8.1 Varieties of Ports - Process Pipes: The [subprocess](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=subprocess.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._subprocess%2529%2529&version=8.18.0.13) function runs a new process at the OS level and returns ports that correspond to the subprocess’s stdin, stdout, and stderr. (The first three arguments can be certain kinds of existing ports to connect directly to the subprocess, instead of creating new ports.) Examples: > ```racket > > ( define-values ( p stdout stdin stderr ) ( subprocess #f #f #f "/usr/bin/wc" "-w" ) ) > > ( display "a b c\n" stdin ) > > ( close-output-port stdin ) > > ( read-line stdout ) > " 3" > > ( close-input-port stdout ) > > ( close-input-port stderr ) > ``` - Internal Pipes: The [make-pipe](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=pipeports.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._make-pipe%2529%2529&version=8.18.0.13) function returns two ports that are ends of a pipe. This kind of pipe is internal to Racket, and not related to OS-level pipes for communicating between different processes. Examples: > ```racket > > ( define-values ( in out ) ( make-pipe ) ) > > ( display "garbage" out ) > > ( close-output-port out ) > > ( read-line in ) > "garbage" > ``` ------------------------------------------------------------------------
# 8.2 Default Ports
### 8.2 Default Ports For most simple I/O functions, the target port is an optional argument, and the default is the current input port or current output port. Furthermore, error messages are written to the current error port, which is an output port. The [current-input-port](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=port-ops.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._current-input-port%2529%2529&version=8.18.0.13), [current-output-port](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=port-ops.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._current-output-port%2529%2529&version=8.18.0.13), and [current-error-port](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=port-ops.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._current-error-port%2529%2529&version=8.18.0.13) functions return the corresponding current ports. Examples: > ```racket > > ( display "Hi" ) > Hi > > ( display "Hi" ( current-output-port ) ) ; the same > Hi > ``` If you start the racket program in a terminal, then the current input, output, and error ports are all connected to the terminal. More generally, they are connected to the OS-level stdin, stdout, and stderr. In this guide, the examples show output written to stdout in purple, and output written to stderr in red italics. Examples:
# 8.2 Default Ports > ```racket > ( define ( swing-hammer ) ( display "Ouch!" ( current-error-port ) ) ) > > ( swing-hammer ) > Ouch! > ``` The current-port functions are actually [parameters](parameterize.html#%28tech._parameter%29), which means that their values can be set with [parameterize](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=parameters.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fmore-scheme..rkt%2529._parameterize%2529%2529&version=8.18.0.13). > > > See [Dynamic Binding: parameterize](parameterize.html) for an introduction to parameters. Example: > ```racket > > ( let ( [ s ( open-output-string ) ] ) ( parameterize ( [ current-error-port s ] ) ( swing-hammer ) ( swing-hammer ) ( swing-hammer ) ) ( get-output-string s ) ) > "Ouch!Ouch!Ouch!" > ``` ------------------------------------------------------------------------
# 8.3 Reading and Writing Racket Data
### 8.3 Reading and Writing Racket Data As noted throughout [Built-In Datatypes](datatypes.html), Racket provides three ways to print an instance of a built-in value: - [print](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Writing.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._print%2529%2529&version=8.18.0.13), which prints a value in the same way that is it printed for a [REPL](intro.html#%28tech._repl%29) result; and - [write](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Writing.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._write%2529%2529&version=8.18.0.13), which prints a value in such a way that [read](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Reading.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._read%2529%2529&version=8.18.0.13) on the output produces the value back; and
# 8.3 Reading and Writing Racket Data - [display](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Writing.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._display%2529%2529&version=8.18.0.13), which tends to reduce a value to just its character or byte content—at least for those datatypes that are primarily about characters or bytes, otherwise it falls back to the same output as [write](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Writing.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._write%2529%2529&version=8.18.0.13). Here are some examples using each:
# 8.3 Reading and Writing Racket Data ``` > ( print 1/2 ) 1/2 > ( print #\x ) #\x > ( print "hello" ) "hello" > ( print #"goodbye" ) #"goodbye" > ( print ' |pea pod| ) '|pea pod| > ( print ' ( "i" pod ) ) '("i" pod) > ( print write ) #<procedure:write>   > ( write 1/2 ) 1/2 > ( write #\x ) #\x > ( write "hello" ) "hello" > ( write #"goodbye" ) #"goodbye" > ( write ' |pea pod| ) |pea pod| > ( write ' ( "i" pod ) ) ("i" pod) > ( write write ) #<procedure:write>   > ( display 1/2 ) 1/2 > ( display #\x ) x > ( display "hello" ) hello > ( display #"goodbye" ) goodbye > ( display ' |pea pod| ) pea pod > ( display ' ( "i" pod ) ) (i pod) > ( display write ) #<procedure:write>``` Overall, [print](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Writing.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._print%2529%2529&version=8.18.0.13) corresponds to the expression layer of Racket syntax, [write](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Writing.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._write%2529%2529&version=8.18.0.13) corresponds to the reader layer, and [display](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Writing.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._display%2529%2529&version=8.18.0.13) roughly corresponds to the character layer. The [printf](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Writing.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._printf%2529%2529&version=8.18.0.13) function supports simple formatting of data and text. In the format string supplied to [printf](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Writing.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._printf%2529%2529&version=8.18.0.13), \~a [display](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Writing.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._display%2529%2529&version=8.18.0.13)s the next argument, \~s [write](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Writing.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._write%2529%2529&version=8.18.0.13)s the next argument, and \~v [print](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Writing.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._print%2529%2529&version=8.18.0.13)s the next argument. Examples: > ```racket > ( define ( deliver who when what ) ( printf "Items ~a for shopper ~s: ~v" who when what ) ) > > ( deliver ' ( "list" ) ' ( "John" ) ' ( "milk" ) ) > Items (list) for shopper ("John"): '("milk") > ``` After using [write](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Writing.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._write%2529%2529&version=8.18.0.13), as opposed to [display](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Writing.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._display%2529%2529&version=8.18.0.13) or [print](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Writing.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._print%2529%2529&version=8.18.0.13), many forms of data can be read back in using [read](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Reading.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._read%2529%2529&version=8.18.0.13). The same values [print](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Writing.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._print%2529%2529&version=8.18.0.13)ed can also be parsed by [read](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Reading.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._read%2529%2529&version=8.18.0.13), but the result may have extra quote forms, since a [print](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Writing.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._print%2529%2529&version=8.18.0.13)ed form is meant to be read like an expression. Examples: > ```racket > > ( define-values ( in out ) ( make-pipe ) ) > > ( write "hello" out ) > > ( read in ) > "hello" > > ( write ' ( "alphabet" soup ) out ) > > ( read in ) > '("alphabet" soup) > > ( write #hash ( ( a . "apple" ) ( b . "banana" ) ) out ) > > ( read in ) > '#hash((a . "apple") (b . "banana")) > > ( print ' ( "alphabet" soup ) out ) > > ( read in ) > ''("alphabet" soup) > > ( display ' ( "alphabet" soup ) out ) > > ( read in ) > '(alphabet soup) > ``` ------------------------------------------------------------------------ # 8.4 Datatypes and Serialization ### 8.4 Datatypes and Serialization [Prefab](define-struct.html#%28tech._prefab%29) structure types (see [Prefab Structure Types](define-struct.html#%28part._prefab-struct%29)) automatically support serialization: they can be written to an output stream, and a copy can be read back in from an input stream: > ```racket > > ( define-values ( in out ) ( make-pipe ) ) > > ( write #s ( sprout bean ) out ) > > ( read in ) > '#s(sprout bean) > ``` Other structure types created by [struct](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=define-struct.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._struct%2529%2529&version=8.18.0.13), which offer more abstraction than [prefab](define-struct.html#%28tech._prefab%29) structure types, normally [write](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Writing.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._write%2529%2529&version=8.18.0.13) either using #\<....> notation (for opaque structure types) or using #(....) vector notation (for transparent structure types). In neither case can the result be read back in as an instance of the structure type: > ```racket > > ( struct posn ( x y ) ) > > ( write ( posn 1 2 ) ) > #<posn> > > ( define-values ( in out ) ( make-pipe ) ) > > ( write ( posn 1 2 ) out ) > > ( read in ) > pipe::1: read: bad syntax `#<`> ``` > ```racket > > ( struct posn ( x y ) #:transparent ) > > ( write ( posn 1 2 ) ) > #(struct:posn 1 2) > > ( define-values ( in out ) ( make-pipe ) ) > > ( write ( posn 1 2 ) out ) > > ( define v ( read in ) ) > > v > '#(struct:posn 1 2) > > ( posn? v ) > #f > > ( vector? v ) > #t > ``` The [serializable-struct](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=serialization.html%23%2528form._%2528%2528lib._racket%252Fserialize..rkt%2529._serializable-struct%2529%2529&version=8.18.0.13) form defines a structure type that can be [serialize](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=serialization.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fserialize..rkt%2529._serialize%2529%2529&version=8.18.0.13)d to a value that can be printed using [write](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Writing.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._write%2529%2529&version=8.18.0.13) and restored via [read](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Reading.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._read%2529%2529&version=8.18.0.13). The [serialize](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=serialization.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fserialize..rkt%2529._serialize%2529%2529&version=8.18.0.13)d result can be [deserialize](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=serialization.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fserialize..rkt%2529._deserialize%2529%2529&version=8.18.0.13)d to get back an instance of the original structure type. The serialization form and functions are provided by the [racket/serialize](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=serialization.html&version=8.18.0.13) library. Examples: > ```racket > > ( require racket/serialize ) > > ( serializable-struct posn ( x y ) #:transparent ) > > ( deserialize ( serialize ( posn 1 2 ) ) ) > (posn 1 2) > > ( write ( serialize ( posn 1 2 ) ) ) > ((3) 1 ((#f . deserialize-info:posn-v0)) 0 () () (0 1 2)) > > ( define-values ( in out ) ( make-pipe ) ) > > ( write ( serialize ( posn 1 2 ) ) out ) > > ( deserialize ( read in ) ) > (posn 1 2) > ``` In addition to the names bound by [struct](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=define-struct.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._struct%2529%2529&version=8.18.0.13), [serializable-struct](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=serialization.html%23%2528form._%2528%2528lib._racket%252Fserialize..rkt%2529._serializable-struct%2529%2529&version=8.18.0.13) binds an identifier with deserialization information, and it automatically [provide](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._provide%2529%2529&version=8.18.0.13)s the deserialization identifier from a module context. This deserialization identifier is accessed reflectively when a value is deserialized. ------------------------------------------------------------------------ # 8.5 Bytes, Characters, and Encodings ### 8.5 Bytes, Characters, and Encodings Functions like [read-line](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Byte_and_String_Input.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._read-line%2529%2529&version=8.18.0.13), [read](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Reading.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._read%2529%2529&version=8.18.0.13), [display](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Writing.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._display%2529%2529&version=8.18.0.13), and [write](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Writing.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._write%2529%2529&version=8.18.0.13) all work in terms of [characters](characters.html#%28tech._character%29) (which correspond to Unicode scalar values). Conceptually, they are implemented in terms of [read-char](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Byte_and_String_Input.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._read-char%2529%2529&version=8.18.0.13) and [write-char](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Byte_and_String_Output.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._write-char%2529%2529&version=8.18.0.13). More primitively, ports read and write [bytes](bytestrings.html#%28tech._byte%29), instead of [characters](characters.html#%28tech._character%29). The functions [read-byte](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Byte_and_String_Input.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._read-byte%2529%2529&version=8.18.0.13) and [write-byte](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Byte_and_String_Output.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._write-byte%2529%2529&version=8.18.0.13) read and write raw bytes. Other functions, such as [read-bytes-line](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Byte_and_String_Input.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._read-bytes-line%2529%2529&version=8.18.0.13), build on top of byte operations instead of character operations. In fact, the [read-char](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Byte_and_String_Input.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._read-char%2529%2529&version=8.18.0.13) and [write-char](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Byte_and_String_Output.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._write-char%2529%2529&version=8.18.0.13) functions are conceptually implemented in terms of [read-byte](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Byte_and_String_Input.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._read-byte%2529%2529&version=8.18.0.13) and [write-byte](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Byte_and_String_Output.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._write-byte%2529%2529&version=8.18.0.13). When a single byte’s value is less than 128, then it corresponds to an ASCII character. Any other byte is treated as part of a UTF-8 sequence, where UTF-8 is a particular standard way of encoding Unicode scalar values in bytes (which has the nice property that ASCII characters are encoded as themselves). Thus, a single [read-char](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Byte_and_String_Input.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._read-char%2529%2529&version=8.18.0.13) may call [read-byte](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Byte_and_String_Input.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._read-byte%2529%2529&version=8.18.0.13) multiple times, and a single [write-char](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Byte_and_String_Output.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._write-char%2529%2529&version=8.18.0.13) may generate multiple output bytes. The [read-char](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Byte_and_String_Input.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._read-char%2529%2529&version=8.18.0.13) and [write-char](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Byte_and_String_Output.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._write-char%2529%2529&version=8.18.0.13) operations always use a UTF-8 encoding. If you have a text stream that uses a different encoding, or if you want to generate a text stream in a different encoding, use [reencode-input-port](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=port-lib.html%23%2528def._%2528%2528lib._racket%252Fport..rkt%2529._reencode-input-port%2529%2529&version=8.18.0.13) or [reencode-output-port](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=port-lib.html%23%2528def._%2528%2528lib._racket%252Fport..rkt%2529._reencode-output-port%2529%2529&version=8.18.0.13). The [reencode-input-port](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=port-lib.html%23%2528def._%2528%2528lib._racket%252Fport..rkt%2529._reencode-input-port%2529%2529&version=8.18.0.13) function converts an input stream from an encoding that you specify into a UTF-8 stream; that way, [read-char](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Byte_and_String_Input.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._read-char%2529%2529&version=8.18.0.13) sees UTF-8 encodings, even though the original used a different encoding. Beware, however, that [read-byte](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Byte_and_String_Input.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._read-byte%2529%2529&version=8.18.0.13) also sees the re-encoded data, instead of the original byte stream. ------------------------------------------------------------------------ # 8.6 I/O Patterns ### 8.6 I/O Patterns > > > ([require](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._require%2529%2529&version=8.18.0.13) racket/port) is needed for [#lang](Module_Syntax.html#%28part._hash-lang%29) [racket/base](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=index.html&version=8.18.0.13). For these examples, say you have two files in the same directory as your program, "oneline.txt" and "manylines.txt". > "oneline.txt" > > > | | > > |------------------------------------------------------------| > > |  I am one line, but there is an empty line after this one. | > > |   | > "manylines.txt" > > > | | > > |--------------------------| > > |  I am | > > |  a message | > > |  split over a few lines. | > > |   | If you have a file that is quite small, you can get away with reading in the file as a string: Examples: > ```racket > > ( define file-contents ( port->string ( open-input-file "oneline.txt" ) #:close? #t ) ) > > ( string-suffix? file-contents "after this one." ) > #f > > ( string-suffix? file-contents "after this one.\n" ) > #t > > ( string-suffix? ( string-trim file-contents ) "after this one." ) > #t > ``` We use [port->string](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=port-lib.html%23%2528def._%2528%2528lib._racket%252Fport..rkt%2529._port-%7E3estring%2529%2529&version=8.18.0.13) from [racket/port](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=port-lib.html&version=8.18.0.13) to do the reading to a string: the #:close? #t keyword argument ensures that our file is closed after the read. We use [string-trim](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=strings.html%23%2528def._%2528%2528lib._racket%252Fstring..rkt%2529._string-trim%2529%2529&version=8.18.0.13) from [racket/string](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=strings.html%23%2528mod-path._racket%252Fstring%2529&version=8.18.0.13) to remove any extraneous whitespace at the very beginning and very end of our file. (Lots of formatters out there insist that text files end with a single blank line). See also [read-line](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Byte_and_String_Input.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._read-line%2529%2529&version=8.18.0.13) if your file has one line of text. If, instead, you want to process individual lines of a file, then you can use [for](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=for.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._for%2529%2529&version=8.18.0.13) with [in-lines](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=sequences.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._in-lines%2529%2529&version=8.18.0.13): > ```racket > > ( define ( upcase-all in ) ( for ( [ l ( in-lines in ) ] ) ( display ( string-upcase l ) ) ( newline ) ) ) > > ( upcase-all ( open-input-string ( string-append "Hello, World!\n" "Can you hear me, now?" ) ) ) > HELLO, WORLD! CAN YOU HEAR ME, NOW? > ``` You could also combine computations over each line. So if you want to know how many lines contain “m”, you could do: Example: > ```racket > > ( with-input-from-file "manylines.txt" ( lambda ( ) ( for/sum ( [ l ( in-lines ) ] #:when ( string-contains? l "m" ) ) 1 ) ) ) > 2 > ``` Here, [with-input-from-file](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=file-ports.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._with-input-from-file%2529%2529&version=8.18.0.13) from [racket/port](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=port-lib.html&version=8.18.0.13) sets the default input port to be the file "manylines.txt" inside the thunk. It also closes the file after the computation has been completed (and in a few other cases). However, if you want to determine whether “hello” appears in a file, then you could search separate lines, but it’s even easier to simply apply a regular expression (see [Regular Expressions](regexp.html)) to the stream: > ```racket > > ( define ( has-hello? in ) ( regexp-match? #rx"hello" in ) ) > > ( has-hello? ( open-input-string "hello" ) ) > #t > > ( has-hello? ( open-input-string "goodbye" ) ) > #f > ``` If you want to copy one port into another, use [copy-port](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=port-lib.html%23%2528def._%2528%2528lib._racket%252Fport..rkt%2529._copy-port%2529%2529&version=8.18.0.13) from [racket/port](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=port-lib.html&version=8.18.0.13), which efficiently transfers large blocks when lots of data is available, but also transfers small blocks immediately if that’s all that is available: > ```racket > > ( define o ( open-output-string ) ) > > ( copy-port ( open-input-string "broom" ) o ) > > ( get-output-string o ) > "broom" > ``` ------------------------------------------------------------------------ # 9 Regular Expressions ## 9 Regular Expressions > > > This chapter is a modified version of \[[Sitaram05](doc-bibliography.html#%28cite._.Sitaram05%29)\]. A regexp value encapsulates a pattern that is described by a string or [byte string](bytestrings.html#%28tech._byte._string%29). The regexp matcher tries to match this pattern against (a portion of) another string or byte string, which we will call the text string, when you call functions like [regexp-match](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=regexp.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._regexp-match%2529%2529&version=8.18.0.13). The text string is treated as raw text, and not as a pattern. | | |------------------------------------------------------------------------------------------------------------------------------------------------------------| |     [9.1 Writing Regexp Patterns](regexp-intro.html) | |     [9.2 Matching Regexp Patterns](regexp-match.html) | |     [9.3 Basic Assertions](regexp-assert.html) | |     [9.4 Characters and Character Classes](regexp-chars.html) | |       [9.4.1 Some Frequently Used Character Classes](regexp-chars.html#%28part._.Some_.Frequently_.Used_.Character_.Classes%29) | |       [9.4.2 POSIX character classes](regexp-chars.html#%28part._.P.O.S.I.X_character_classes%29) | |     [9.5 Quantifiers](regexp-quant.html) | |     [9.6 Clusters](regexp-clusters.html) | |       [9.6.1 Backreferences](regexp-clusters.html#%28part._.Backreferences%29) | |       [9.6.2 Non-capturing Clusters](regexp-clusters.html#%28part._.Non-capturing_.Clusters%29) | |       [9.6.3 Cloisters](regexp-clusters.html#%28part._regexp-cloister%29) | |     [9.7 Alternation](regexp-alternation.html) | |     [9.8 Backtracking](Backtracking.html) | |     [9.9 Looking Ahead and Behind](Looking_Ahead_and_Behind.html) | |       [9.9.1 Lookahead](Looking_Ahead_and_Behind.html#%28part._.Lookahead%29) | |       [9.9.2 Lookbehind](Looking_Ahead_and_Behind.html#%28part._.Lookbehind%29) | |     [9.10 An Extended Example](An_Extended_Example.html) | > > > <img src="magnify.png" width="24" height="24" alt="+" />[Regular Expressions](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=regexp.html&version=8.18.0.13) in [The Racket Reference](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=index.html&version=8.18.0.13) provides more on regexps. ------------------------------------------------------------------------ # 9.1 Writing Regexp Patterns ### 9.1 Writing Regexp Patterns A string or [byte string](bytestrings.html#%28tech._byte._string%29) can be used directly as a [regexp](regexp.html#%28tech._regexp%29) pattern, or it can be prefixed with #rx to form a literal [regexp](regexp.html#%28tech._regexp%29) value. For example, #rx"abc" is a string-based [regexp](regexp.html#%28tech._regexp%29) value, and #rx#"abc" is a [byte string](bytestrings.html#%28tech._byte._string%29)-based [regexp](regexp.html#%28tech._regexp%29) value. Alternately, a string or byte string can be prefixed with #px, as in #px"abc", for a slightly extended syntax of patterns within the string. Most of the characters in a [regexp](regexp.html#%28tech._regexp%29) pattern are meant to match occurrences of themselves in the [text string](regexp.html#%28tech._text._string%29). Thus, the pattern #rx"abc" matches a string that contains the characters a, b, and c in succession. Other characters act as metacharacters, and some character sequences act as metasequences. That is, they specify something other than their literal selves. For example, in the pattern #rx"a.c", the characters a and c stand for themselves, but the [metacharacter](#%28tech._metacharacter%29) . can match any character. Therefore, the pattern #rx"a.c" matches an a, any character, and c in succession. > > > When we want a literal \\ inside a Racket string or regexp literal, we must escape it so that it shows up in the string at all. Racket strings use \\ as the escape character, so we end up with two \\s: one Racket-string \\ to escape the regexp \\, which then escapes the .. Another character that would need escaping inside a Racket string is ". If we needed to match the character . itself, we can escape it by preceding it with a \\. The character sequence \\. is thus a [metasequence](#%28tech._metasequence%29), since it doesn’t match itself but rather just .. So, to match a, ., and c in succession, we use the regexp pattern #rx"a\\\\.c"; the double \\ is an artifact of Racket strings, not the [regexp](regexp.html#%28tech._regexp%29) pattern itself. The [regexp](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=regexp.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._regexp%2529%2529&version=8.18.0.13) function takes a string or byte string and produces a [regexp](regexp.html#%28tech._regexp%29) value. Use [regexp](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=regexp.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._regexp%2529%2529&version=8.18.0.13) when you construct a pattern to be matched against multiple strings, since a pattern is compiled to a [regexp](regexp.html#%28tech._regexp%29) value before it can be used in a match. The [pregexp](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=regexp.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._pregexp%2529%2529&version=8.18.0.13) function is like [regexp](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=regexp.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._regexp%2529%2529&version=8.18.0.13), but using the extended syntax. Regexp values as literals with #rx or #px are compiled once and for all when they are read. The [regexp-quote](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=regexp.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._regexp-quote%2529%2529&version=8.18.0.13) function takes an arbitrary string and returns a string for a pattern that matches exactly the original string. In particular, characters in the input string that could serve as regexp metacharacters are escaped with a backslash, so that they safely match only themselves. > ```racket > > ( regexp-quote "cons" ) > "cons" > > ( regexp-quote "list?" ) > "list\\?" > ``` The [regexp-quote](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=regexp.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._regexp-quote%2529%2529&version=8.18.0.13) function is useful when building a composite [regexp](regexp.html#%28tech._regexp%29) from a mix of [regexp](regexp.html#%28tech._regexp%29) strings and verbatim strings. ------------------------------------------------------------------------ # 9.2 Matching Regexp Patterns ### 9.2 Matching Regexp Patterns The [regexp-match-positions](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=regexp.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._regexp-match-positions%2529%2529&version=8.18.0.13) function takes a [regexp](regexp.html#%28tech._regexp%29) pattern and a [text string](regexp.html#%28tech._text._string%29), and it returns a match if the regexp matches (some part of) the [text string](regexp.html#%28tech._text._string%29), or #f if the regexp did not match the string. A successful match produces a list of index pairs. Examples: > ```racket > > ( regexp-match-positions #rx"brain" "bird" ) > #f > > ( regexp-match-positions #rx"needle" "hay needle stack" ) > '((4 . 10)) > ``` In the second example, the integers 4 and 10 identify the substring that was matched. The 4 is the starting (inclusive) index, and 10 the ending (exclusive) index of the matching substring: > ```racket > > ( substring "hay needle stack" 4 10 ) > "needle" > ``` In this first example, [regexp-match-positions](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=regexp.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._regexp-match-positions%2529%2529&version=8.18.0.13)’s return list contains only one index pair, and that pair represents the entire substring matched by the regexp. When we discuss [subpatterns](regexp-clusters.html#%28tech._subpattern%29) later, we will see how a single match operation can yield a list of [submatch](regexp-clusters.html#%28tech._submatch%29)es. The [regexp-match-positions](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=regexp.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._regexp-match-positions%2529%2529&version=8.18.0.13) function takes optional third and fourth arguments that specify the indices of the [text string](regexp.html#%28tech._text._string%29) within which the matching should take place. > ```racket > > ( regexp-match-positions #rx"needle" "his needle stack -- my needle stack -- her needle stack" 20 39 ) > '((23 . 29)) > ``` Note that the returned indices are still reckoned relative to the full [text string](regexp.html#%28tech._text._string%29). The [regexp-match](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=regexp.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._regexp-match%2529%2529&version=8.18.0.13) function is like [regexp-match-positions](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=regexp.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._regexp-match-positions%2529%2529&version=8.18.0.13), but instead of returning index pairs, it returns the matching substrings: > ```racket > > ( regexp-match #rx"brain" "bird" ) > #f > > ( regexp-match #rx"needle" "hay needle stack" ) > '("needle") > ``` When [regexp-match](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=regexp.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._regexp-match%2529%2529&version=8.18.0.13) is used with byte-string regexp, the result is a matching byte substring: > ```racket > > ( regexp-match #rx#"needle" #"hay needle stack" ) > '(#"needle") > ``` > > > A byte-string regexp can be applied to a string, and a string regexp can be applied to a byte string. In both cases, the result is a byte string. Internally, all regexp matching is in terms of bytes, and a string regexp is expanded to a regexp that matches UTF-8 encodings of characters. For maximum efficiency, use byte-string matching instead of string, since matching bytes directly avoids UTF-8 encodings. If you have data that is in a port, there’s no need to first read it into a string. Functions like [regexp-match](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=regexp.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._regexp-match%2529%2529&version=8.18.0.13) can match on the port directly: > ```racket > > ( define-values ( i o ) ( make-pipe ) ) > > ( write "hay needle stack" o ) > > ( close-output-port o ) > > ( regexp-match #rx#"needle" i ) > '(#"needle") > ``` The [regexp-match?](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=regexp.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._regexp-match%7E3f%2529%2529&version=8.18.0.13) function is like [regexp-match-positions](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=regexp.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._regexp-match-positions%2529%2529&version=8.18.0.13), but simply returns a boolean indicating whether the match succeeded: > ```racket > > ( regexp-match? #rx"brain" "bird" ) > #f > > ( regexp-match? #rx"needle" "hay needle stack" ) > #t > ``` The [regexp-split](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=regexp.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._regexp-split%2529%2529&version=8.18.0.13) function takes two arguments, a [regexp](regexp.html#%28tech._regexp%29) pattern and a text string, and it returns a list of substrings of the text string; the pattern identifies the delimiter separating the substrings. > ```racket > > ( regexp-split #rx":" "/bin:/usr/bin:/usr/bin/X11:/usr/local/bin" ) > '("/bin" "/usr/bin" "/usr/bin/X11" "/usr/local/bin") > > ( regexp-split #rx" " "pea soup" ) > '("pea" "soup") > ``` If the first argument matches empty strings, then the list of all the single-character substrings is returned. > ```racket > > ( regexp-split #rx"" "smithereens" ) > '("" "s" "m" "i" "t" "h" "e" "r" "e" "e" "n" "s" "") > ``` Thus, to identify one-or-more spaces as the delimiter, take care to use the regexp #rx" +", not #rx" \*". > ```racket > > ( regexp-split #rx" +" "split pea soup" ) > '("split" "pea" "soup") > > ( regexp-split #rx" *" "split pea soup" ) > '("" "s" "p" "l" "i" "t" "" "p" "e" "a" "" "s" "o" "u" "p" "") > ``` The [regexp-replace](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=regexp.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._regexp-replace%2529%2529&version=8.18.0.13) function replaces the matched portion of the text string by another string. The first argument is the pattern, the second the text string, and the third is either the string to be inserted or a procedure to convert matches to the insert string. > ```racket > > ( regexp-replace #rx"te" "liberte" "ty" ) > "liberty" > > ( regexp-replace #rx"." "racket" string-upcase ) > "Racket" > ``` If the pattern doesn’t occur in the text string, the returned string is identical to the text string. The [regexp-replace*](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=regexp.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._regexp-replace%252A%2529%2529&version=8.18.0.13) function replaces all matches in the text string by the insert string: > ```racket > > ( regexp-replace* #rx"te" "liberte egalite fraternite" "ty" ) > "liberty egality fratyrnity" > > ( regexp-replace* #rx"[ds]" "drracket" string-upcase ) > "Drracket" > ``` ------------------------------------------------------------------------ # 9.3 Basic Assertions ### 9.3 Basic Assertions The assertions ^ and $ identify the beginning and the end of the text string, respectively. They ensure that their adjoining regexps match at one or other end of the text string: > ```racket > > ( regexp-match-positions #rx"^contact" "first contact" ) > #f > ``` The [regexp](regexp.html#%28tech._regexp%29) above fails to match because contact does not occur at the beginning of the text string. In > ```racket > > ( regexp-match-positions #rx"laugh$" "laugh laugh laugh laugh" ) > '((18 . 23)) > ``` the regexp matches the last laugh. The metasequence \\b asserts that a word boundary exists, but this metasequence works only with #px syntax. In > ```racket > > ( regexp-match-positions #px"yack\\b" "yackety yack" ) > '((8 . 12)) > ``` the yack in yackety doesn’t end at a word boundary so it isn’t matched. The second yack does and is. The metasequence \\B (also #px only) has the opposite effect to \\b; it asserts that a word boundary does not exist. In > ```racket > > ( regexp-match-positions #px"an\\B" "an analysis" ) > '((3 . 5)) > ``` the an that doesn’t end in a word boundary is matched. ------------------------------------------------------------------------ # 9.4 Characters and Character Classes ### 9.4 Characters and Character Classes Typically, a character in the regexp matches the same character in the text string. Sometimes it is necessary or convenient to use a regexp [metasequence](regexp-intro.html#%28tech._metasequence%29) to refer to a single character. For example, the metasequence \\. matches the period character. The [metacharacter](regexp-intro.html#%28tech._metacharacter%29) . matches any character (other than newline in [multi-line mode](regexp-clusters.html#%28tech._multi._line._mode%29); see [Cloisters](regexp-clusters.html#%28part._regexp-cloister%29)): > ```racket > > ( regexp-match #rx"p.t" "pet" ) > '("pet") > ``` The above pattern also matches pat, pit, pot, put, and p8t, but not peat or pfffft. A character class matches any one character from a set of characters. A typical format for this is the bracketed character class \[...\], which matches any one character from the non-empty sequence of characters enclosed within the brackets. Thus, #rx"p\[aeiou\]t" matches pat, pet, pit, pot, put, and nothing else. Inside the brackets, a - between two characters specifies the Unicode range between the characters. For example, #rx"ta\[b-dgn-p\]" matches tab, tac, tad, tag, tan, tao, and tap. An initial ^ after the left bracket inverts the set specified by the rest of the contents; i.e., it specifies the set of characters other than those identified in the brackets. For example, #rx"do\[^g\]" matches all three-character sequences starting with do except dog. Note that the [metacharacter](regexp-intro.html#%28tech._metacharacter%29) ^ inside brackets means something quite different from what it means outside. Most other [metacharacters](regexp-intro.html#%28tech._metacharacter%29) (., \*, +, ?, etc.) cease to be [metacharacters](regexp-intro.html#%28tech._metacharacter%29) when inside brackets, although you may still escape them for peace of mind. A - is a [metacharacter](regexp-intro.html#%28tech._metacharacter%29) only when it’s inside brackets, and when it is neither the first nor the last character between the brackets. Bracketed character classes cannot contain other bracketed character classes (although they contain certain other types of character classes; see below). Thus, a \[ inside a bracketed character class doesn’t have to be a metacharacter; it can stand for itself. For example, #rx"\[a\[b\]" matches a, \[, and b. Furthermore, since empty bracketed character classes are disallowed, a \] immediately occurring after the opening left bracket also doesn’t need to be a metacharacter. For example, #rx"\[\]ab\]" matches \], a, and b. #### 9.4.1 Some Frequently Used Character Classes In #px syntax, some standard character classes can be conveniently represented as metasequences instead of as explicit bracketed expressions: \\d matches a digit (the same as \[0-9\]); \\s matches an ASCII whitespace character; and \\w matches a character that could be part of a “word”. > > > Following regexp custom, we identify “word” characters as \[A-Za-z0-9\_\], although these are too restrictive for what a Racketeer might consider a “word.” The upper-case versions of these metasequences stand for the inversions of the corresponding character classes: \\D matches a non-digit, \\S a non-whitespace character, and \\W a non-“word” character. Remember to include a double backslash when putting these metasequences in a Racket string: > ```racket > > ( regexp-match #px"\\d\\d" "0 dear, 1 have 2 read catch 22 before 9" ) > '("22") > ``` These character classes can be used inside a bracketed expression. For example, #px"\[a-z\\\\d\]" matches a lower-case letter or a digit. #### 9.4.2 POSIX character classes A POSIX character class is a special [metasequence](regexp-intro.html#%28tech._metasequence%29) of the form \[:...:\] that can be used only inside a bracketed expression in #px syntax. The POSIX classes supported are - \[:alnum:\] — ASCII letters and digits - \[:alpha:\] — ASCII letters - \[:ascii:\] — ASCII characters - \[:blank:\] — ASCII widthful whitespace: space and tab - \[:cntrl:\] — “control” characters: ASCII 0 to 31 - \[:digit:\] — ASCII digits, same as \\d - \[:graph:\] — ASCII characters that use ink - \[:lower:\] — ASCII lower-case letters - \[:print:\] — ASCII ink-users plus widthful whitespace - \[:space:\] — ASCII whitespace, same as \\s - \[:upper:\] — ASCII upper-case letters - \[:word:\] — ASCII letters and \_, same as \\w - \[:xdigit:\] — ASCII hex digits For example, the #px"\[\[:alpha:\]\_\]" matches a letter or underscore. > ```racket > > ( regexp-match #px"[[:alpha:]_]" "--x--" ) > '("x") > > ( regexp-match #px"[[:alpha:]_]" "--_--" ) > '("_") > > ( regexp-match #px"[[:alpha:]_]" "--:--" ) > #f > ``` The POSIX class notation is valid only inside a bracketed expression. For instance, \[:alpha:\], when not inside a bracketed expression, will not be read as the letter class. Rather, it is (from previous principles) the character class containing the characters :, a, l, p, h. > ```racket > > ( regexp-match #px"[:alpha:]" "--a--" ) > '("a") > > ( regexp-match #px"[:alpha:]" "--x--" ) > #f > ``` ------------------------------------------------------------------------ # 9.5 Quantifiers ### 9.5 Quantifiers The quantifiers \*, +, and ? match respectively: zero or more, one or more, and zero or one instances of the preceding subpattern. > ```racket > > ( regexp-match-positions #rx"c[ad]*r" "cadaddadddr" ) > '((0 . 11)) > > ( regexp-match-positions #rx"c[ad]*r" "cr" ) > '((0 . 2)) > > ( regexp-match-positions #rx"c[ad]+r" "cadaddadddr" ) > '((0 . 11)) > > ( regexp-match-positions #rx"c[ad]+r" "cr" ) > #f > > ( regexp-match-positions #rx"c[ad]?r" "cadaddadddr" ) > #f > > ( regexp-match-positions #rx"c[ad]?r" "cr" ) > '((0 . 2)) > > ( regexp-match-positions #rx"c[ad]?r" "car" ) > '((0 . 3)) > ``` In #px syntax, you can use braces to specify much finer-tuned quantification than is possible with \*, +, ?: - The quantifier {m} matches exactly m instances of the preceding [subpattern](regexp-clusters.html#%28tech._subpattern%29); m must be a nonnegative integer. - The quantifier {m,n} matches at least m and at most n instances. m and n are nonnegative integers with m less or equal to n. You may omit either or both numbers, in which case m defaults to 0 and n to infinity. It is evident that + and ? are abbreviations for {1,} and {0,1} respectively, and \* abbreviates {,}, which is the same as {0,}. > ```racket > > ( regexp-match #px"[aeiou]{3}" "vacuous" ) > '("uou") > > ( regexp-match #px"[aeiou]{3}" "evolve" ) > #f > > ( regexp-match #px"[aeiou]{2,3}" "evolve" ) > #f > > ( regexp-match #px"[aeiou]{2,3}" "zeugma" ) > '("eu") > ``` The quantifiers described so far are all greedy: they match the maximal number of instances that would still lead to an overall match for the full pattern. > ```racket > > ( regexp-match #rx"<.*>" "<tag1> <tag2> <tag3>" ) > '("<tag1> <tag2> <tag3>") > ``` To make these quantifiers non-greedy, append a ? to them. Non-greedy quantifiers match the minimal number of instances needed to ensure an overall match. > ```racket > > ( regexp-match #rx"<.*?>" "<tag1> <tag2> <tag3>" ) > '("<tag1>") > ``` The non-greedy quantifiers are \*?, +?, ??, {m}?, and {m,n}?, although {m}? is always the same as {m}. Note that the metacharacter ? has two different uses, and both uses are represented in ??. ------------------------------------------------------------------------ # 9.6 Clusters ### 9.6 Clusters Clustering—enclosure within parens (...)—identifies the enclosed subpattern as a single entity. It causes the matcher to capture the submatch, or the portion of the string matching the subpattern, in addition to the overall match: > ```racket > > ( regexp-match #rx"([a-z]+) ([0-9]+), ([0-9]+)" "jan 1, 1970" ) > '("jan 1, 1970" "jan" "1" "1970") > ``` Clustering also causes a following quantifier to treat the entire enclosed subpattern as an entity: > ```racket > > ( regexp-match #rx"(pu )*" "pu pu platter" ) > '("pu pu " "pu ") > ``` The number of submatches returned is always equal to the number of subpatterns specified in the regexp, even if a particular subpattern happens to match more than one substring or no substring at all. > ```racket > > ( regexp-match #rx"([a-z ]+;)*" "lather; rinse; repeat;" ) > '("lather; rinse; repeat;" " repeat;") > ``` Here, the \*-quantified subpattern matches three times, but it is the last submatch that is returned. It is also possible for a quantified subpattern to fail to match, even if the overall pattern matches. In such cases, the failing submatch is represented by #f > ```racket > > ( define date-re ; match ‘ month year ' or ‘ month day, year ' ; ; subpattern matches day, if present #rx"([a-z]+) +([0-9]+,)? *([0-9]+)" ) > > ( regexp-match date-re "jan 1, 1970" ) > '("jan 1, 1970" "jan" "1," "1970") > > ( regexp-match date-re "jan 1970" ) > '("jan 1970" "jan" #f "1970") > ``` #### 9.6.1 Backreferences [Submatch](#%28tech._submatch%29)es can be used in the insert string argument of the procedures [regexp-replace](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=regexp.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._regexp-replace%2529%2529&version=8.18.0.13) and [regexp-replace*](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=regexp.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._regexp-replace%252A%2529%2529&version=8.18.0.13). The insert string can use \\n as a backreference to refer back to the nth submatch, which is the substring that matched the nth subpattern. A \\0 refers to the entire match, and it can also be specified as \\&. > ```racket > > ( regexp-replace #rx"_(.+?)_" "the _nina_, the _pinta_, and the _santa maria_" "*\\1*" ) > "the *nina*, the _pinta_, and the _santa maria_" > > ( regexp-replace* #rx"_(.+?)_" "the _nina_, the _pinta_, and the _santa maria_" "*\\1*" ) > "the *nina*, the *pinta*, and the *santa maria*" > > ( regexp-replace #px"(\\S+) (\\S+) (\\S+)" "eat to live" "\\3 \\2 \\1" ) > "live to eat" > ``` Use \\\\ in the insert string to specify a literal backslash. Also, \\$ stands for an empty string, and is useful for separating a backreference \\n from an immediately following number. Backreferences can also be used within a #px pattern to refer back to an already matched subpattern in the pattern. \\n stands for an exact repeat of the nth submatch. Note that \\0, which is useful in an insert string, makes no sense within the regexp pattern, because the entire regexp has not matched yet so you cannot refer back to it.} > ```racket > > ( regexp-match #px"([a-z]+) and \\1" "billions and billions" ) > '("billions and billions" "billions") > ``` Note that the [backreference](#%28tech._backreference%29) is not simply a repeat of the previous subpattern. Rather it is a repeat of the particular substring already matched by the subpattern. In the above example, the [backreference](#%28tech._backreference%29) can only match billions. It will not match millions, even though the subpattern it harks back to—(\[a-z\]+)—would have had no problem doing so: > ```racket > > ( regexp-match #px"([a-z]+) and \\1" "billions and millions" ) > #f > ``` The following example marks all immediately repeating patterns in a number string: > ```racket > > ( regexp-replace* #px"(\\d+)\\1" "123340983242432420980980234" "{\\1,\\1}" ) > "12{3,3}40983{24,24}3242{098,098}0234" > ``` The following example corrects doubled words: > ```racket > > ( regexp-replace* #px"\\b(\\S+) \\1\\b" ( string-append "now is the the time for all good men to " "to come to the aid of of the party" ) "\\1" ) > "now is the time for all good men to come to the aid of the party" > ``` #### 9.6.2 Non-capturing Clusters It is often required to specify a cluster (typically for quantification) but without triggering the capture of [submatch](#%28tech._submatch%29) information. Such clusters are called non-capturing. To create a non-capturing cluster, use (?: instead of ( as the cluster opener. In the following example, a non-capturing cluster eliminates the “directory” portion of a given Unix pathname, and a capturing cluster identifies the basename. > > > But don’t parse paths with regexps. Use functions like [split-path](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Manipulating_Paths.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._split-path%2529%2529&version=8.18.0.13), instead. > ```racket > > ( regexp-match #rx"^(?:[a-z]*/)*([a-z]+)$" "/usr/local/bin/racket" ) > '("/usr/local/bin/racket" "racket") > ``` #### 9.6.3 Cloisters The location between the ? and the : of a non-capturing cluster is called a cloister. You can put modifiers there that will cause the enclustered [subpattern](#%28tech._subpattern%29) to be treated specially. The modifier i causes the subpattern to match case-insensitively: > > > The term cloister is a useful, if terminally cute, coinage from the abbots of Perl. > ```racket > > ( regexp-match #rx"(?i:hearth)" "HeartH" ) > '("HeartH") > ``` The modifier m causes the [subpattern](#%28tech._subpattern%29) to match in multi-line mode, where . does not match a newline character, ^ can match just after a newline, and $ can match just before a newline. > ```racket > > ( regexp-match #rx"." "\na\n" ) > '("\n") > > ( regexp-match #rx"(?m:.)" "\na\n" ) > '("a") > > ( regexp-match #rx"^A plan$" "A man\nA plan\nA canal" ) > #f > > ( regexp-match #rx"(?m:^A plan$)" "A man\nA plan\nA canal" ) > '("A plan") > ``` You can put more than one modifier in the cloister: > ```racket > > ( regexp-match #rx"(?mi:^A Plan$)" "a man\na plan\na canal" ) > '("a plan") > ``` A minus sign before a modifier inverts its meaning. Thus, you can use -i in a subcluster to overturn the case-insensitivities caused by an enclosing cluster. > ```racket > > ( regexp-match #rx"(?i:the (?-i:TeX)book)" "The TeXbook" ) > '("The TeXbook") > ``` The above regexp will allow any casing for the and book, but it insists that TeX not be differently cased. ------------------------------------------------------------------------ # 9.7 Alternation ### 9.7 Alternation You can specify a list of alternate [subpatterns](regexp-clusters.html#%28tech._subpattern%29) by separating them by \|. The \| separates [subpatterns](regexp-clusters.html#%28tech._subpattern%29) in the nearest enclosing cluster (or in the entire pattern string if there are no enclosing parens). > ```racket > > ( regexp-match #rx"f(ee|i|o|um)" "a small, final fee" ) > '("fi" "i") > > ( regexp-replace* #rx"([yi])s(e[sdr]?|ing|ation)" ( string-append "analyse an energising organisation" " pulsing with noisy organisms" ) "\\1z\\2" ) > "analyze an energizing organization pulsing with noisy organisms" > ``` Note again that if you wish to use clustering merely to specify a list of alternate subpatterns but do not want the submatch, use (?: instead of (. > ```racket > > ( regexp-match #rx"f(?:ee|i|o|um)" "fun for all" ) > '("fo") > ``` An important thing to note about alternation is that the leftmost matching alternate is picked regardless of its length. Thus, if one of the alternates is a prefix of a later alternate, the latter may not have a chance to match. > ```racket > > ( regexp-match #rx"call|call-with-current-continuation" "call-with-current-continuation" ) > '("call") > ``` To allow the longer alternate to have a shot at matching, place it before the shorter one: > ```racket > > ( regexp-match #rx"call-with-current-continuation|call" "call-with-current-continuation" ) > '("call-with-current-continuation") > ``` In any case, an overall match for the entire regexp is always preferred to an overall non-match. In the following, the longer alternate still wins, because its preferred shorter prefix fails to yield an overall match. > ```racket > > ( regexp-match #rx"(?:call|call-with-current-continuation) constrained" "call-with-current-continuation constrained" ) > '("call-with-current-continuation constrained") > ``` ------------------------------------------------------------------------ # 9.8 Backtracking ### 9.8 Backtracking We’ve already seen that greedy quantifiers match the maximal number of times, but the overriding priority is that the overall match succeed. Consider > ```racket > > ( regexp-match #rx"a*a" "aaaa" ) > '("aaaa") > ``` The regexp consists of two subregexps: a\* followed by a. The subregexp a\* cannot be allowed to match all four a’s in the text string aaaa, even though \* is a greedy quantifier. It may match only the first three, leaving the last one for the second subregexp. This ensures that the full regexp matches successfully. The regexp matcher accomplishes this via a process called backtracking. The matcher tentatively allows the greedy quantifier to match all four a’s, but then when it becomes clear that the overall match is in jeopardy, it backtracks to a less greedy match of three a’s. If even this fails, as in the call > ```racket > > ( regexp-match #rx"a*aa" "aaaa" ) > '("aaaa") > ``` the matcher backtracks even further. Overall failure is conceded only when all possible backtracking has been tried with no success. Backtracking is not restricted to greedy quantifiers. Nongreedy quantifiers match as few instances as possible, and progressively backtrack to more and more instances in order to attain an overall match. There is backtracking in alternation too, as the more rightward alternates are tried when locally successful leftward ones fail to yield an overall match. Sometimes it is efficient to disable backtracking. For example, we may wish to commit to a choice, or we know that trying alternatives is fruitless. A nonbacktracking regexp is enclosed in (?>...). > ```racket > > ( regexp-match #rx"(?>a+)." "aaaa" ) > #f > ``` In this call, the subregexp ?>a+ greedily matches all four a’s, and is denied the opportunity to backtrack. So, the overall match is denied. The effect of the regexp is therefore to match one or more a’s followed by something that is definitely non-a. ------------------------------------------------------------------------ # 9.9 Looking Ahead and Behind ### 9.9 Looking Ahead and Behind You can have assertions in your pattern that look ahead or behind to ensure that a subpattern does or does not occur. These “look around” assertions are specified by putting the subpattern checked for in a cluster whose leading characters are: ?= (for positive lookahead), ?! (negative lookahead), ?\<= (positive lookbehind), ?\<! (negative lookbehind). Note that the subpattern in the assertion does not generate a match in the final result; it merely allows or disallows the rest of the match. #### 9.9.1 Lookahead Positive lookahead with ?= peeks ahead to ensure that its subpattern could match. > ```racket > > ( regexp-match-positions #rx"grey(?=hound)" "i left my grey socks at the greyhound" ) > '((28 . 32)) > ``` The regexp #rx"grey(?=hound)" matches grey, but only if it is followed by hound. Thus, the first grey in the text string is not matched. Negative lookahead with ?! peeks ahead to ensure that its subpattern could not possibly match. > ```racket > > ( regexp-match-positions #rx"grey(?!hound)" "the gray greyhound ate the grey socks" ) > '((27 . 31)) > ``` The regexp #rx"grey(?!hound)" matches grey, but only if it is not followed by hound. Thus the grey just before socks is matched. #### 9.9.2 Lookbehind Positive lookbehind with ?\<= checks that its subpattern could match immediately to the left of the current position in the text string.> ```racket > > ( regexp-match-positions #rx"(?<=grey)hound" "the hound in the picture is not a greyhound" )> '((38 . 43)) > ``` The regexp #rx"(?\<=grey)hound" matches hound, but only if it is preceded by grey. Negative lookbehind with ?\<! checks that its subpattern could not possibly match immediately to the left.> ```racket > > ( regexp-match-positions #rx"(?<!grey)hound" "the greyhound in the picture is not a hound" )> '((38 . 43)) > ``` The regexp #rx"(?\<!grey)hound" matches hound, but only if it is not preceded by grey. Lookaheads and lookbehinds can be convenient when they are not confusing. ------------------------------------------------------------------------ # 9.10 An Extended Example ### 9.10 An Extended Example Here’s an extended example from Friedl’s Mastering Regular Expressions, page 189, that covers many of the features described in this chapter. The problem is to fashion a regexp that will match any and only IP addresses or dotted quads: four numbers separated by three dots, with each number between 0 and 255. First, we define a subregexp n0-255 that matches 0 through 255: > ```racket > > ( define n0-255 ( string-append "(?:" "\\d|" ; 0 through 9 "\\d\\d|" ; 00 through 99 "[01]\\d\\d|" ; 000 through 199 "2[0-4]\\d|" ; 200 through 249 "25[0-5]" ; 250 through 255 ")" ) ) > ``` > > > Note that n0-255 lists prefixes as preferred alternates, which is something we cautioned against in [Alternation](regexp-alternation.html). However, since we intend to anchor this subregexp explicitly to force an overall match, the order of the alternates does not matter. The first two alternates simply get all single- and double-digit numbers. Since 0-padding is allowed, we need to match both 1 and 01. We need to be careful when getting 3-digit numbers, since numbers above 255 must be excluded. So we fashion alternates to get 000 through 199, then 200 through 249, and finally 250 through 255. An IP-address is a string that consists of four n0-255s with three dots separating them. > ```racket > > ( define ip-re1 ( string-append "^" ; nothing before n0-255 ; the first n0-255 , "(?:" ; then the subpattern of "\\." ; a dot followed by n0-255 ; an n0-255 , ")" ; which is "{3}" ; repeated exactly 3 times "$" ) ) > ; with nothing following > ``` Let’s try it out: > ```racket > > ( regexp-match ( pregexp ip-re1 ) "1.2.3.4" ) > '("1.2.3.4") > > ( regexp-match ( pregexp ip-re1 ) "55.155.255.265" ) > #f > ``` which is fine, except that we also have > ```racket > > ( regexp-match ( pregexp ip-re1 ) "0.00.000.00" ) > '("0.00.000.00") > ``` All-zero sequences are not valid IP addresses! Lookahead to the rescue. Before starting to match ip-re1, we look ahead to ensure we don’t have all zeros. We could use positive lookahead to ensure there is a digit other than zero. > ```racket > > ( define ip-re ( pregexp ( string-append "(?=.*[1-9])" ; ensure there ' s a non-0 digit ip-re1 ) ) ) > ``` Or we could use negative lookahead to ensure that what’s ahead isn’t composed of only zeros and dots. > ```racket > > ( define ip-re ( pregexp ( string-append "(?![0.]*$)" ; not just zeros and dots ; (note: . is not metachar inside [ ... ] ) ip-re1 ) ) ) > ``` The regexp ip-re will match all and only valid IP addresses. > ```racket > > ( regexp-match ip-re "1.2.3.4" ) > '("1.2.3.4") > > ( regexp-match ip-re "0.0.0.0" ) > #f > ``` ------------------------------------------------------------------------ # 10 Exceptions and Control ## 10 Exceptions and Control Racket provides an especially rich set of control operations—not only operations for raising and catching exceptions, but also operations for grabbing and restoring portions of a computation. | | |-----------------------------------------------------------------------| |     [10.1 Exceptions](exns.html) | |     [10.2 Prompts and Aborts](prompt.html) | |     [10.3 Continuations](conts.html) | ------------------------------------------------------------------------ # 10.1 Exceptions ### 10.1 Exceptions Whenever a run-time error occurs, an exception is raised. Unless the exception is caught, then it is handled by printing a message associated with the exception, and then escaping from the computation. > ```racket > > ( / 1 0 ) > /: division by zero > > ( car 17 ) > car: contract violation > expected: pair? > given: 17 > ``` To catch an exception, use the [with-handlers](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=exns.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fmore-scheme..rkt%2529._with-handlers%2529%2529&version=8.18.0.13) form: > > ``` (with-handlers ([predicate-expr handler-expr] ...) > > body ...+ ) ```
# 8.3 Reading and Writing Racket Data (v) → (-> with-handlers ([ exn:fail? (lambda (v) ((error-display-handler) (exn-message v) v)) ]) (car 17))``` A [for](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=for.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._for%2529%2529&version=8.18.0.13) loop iterates through the sequence produced by the sequence-expr. For each element of the sequence, [for](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=for.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._for%2529%2529&version=8.18.0.13) binds the element to id, and then it evaluates the bodys for side effects. Examples: > ```racket > > ( for ( [ i ' ( 1 2 3 ) ] ) ( display i ) ) > 123 > > ( for ( [ i "abc" ] ) ( printf "~a..." i ) ) > a...b...c... > > ( for ( [ i 4 ] ) ( display i ) ) > 0123 > ```
# 8.3 Reading and Writing Racket Data The [for/list](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=for.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._for%252Flist%2529%2529&version=8.18.0.13) variant of [for](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=for.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._for%2529%2529&version=8.18.0.13) is more Racket-like. It accumulates body results into a list, instead of evaluating body only for side effects. In more technical terms, [for/list](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=for.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._for%252Flist%2529%2529&version=8.18.0.13) implements a list comprehension. Examples: > ```racket > > ( for/list ( [ i ' ( 1 2 3 ) ] ) ( * i i ) ) > '(1 4 9) > > ( for/list ( [ i "abc" ] ) i ) > '(#\a #\b #\c) > > ( for/list ( [ i 4 ] ) i ) > '(0 1 2 3) > ```
# 8.3 Reading and Writing Racket Data The full syntax of [for](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=for.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._for%2529%2529&version=8.18.0.13) accommodates multiple sequences to iterate in parallel, and the [for*](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=for.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._for%252A%2529%2529&version=8.18.0.13) variant nests the iterations instead of running them in parallel. More variants of [for](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=for.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._for%2529%2529&version=8.18.0.13) and [for*](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=for.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._for%252A%2529%2529&version=8.18.0.13) accumulate body results in different ways. In all of these variants, predicates that prune iterations can be included along with bindings.
# 8.3 Reading and Writing Racket Data Before details on the variations of [for](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=for.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._for%2529%2529&version=8.18.0.13), though, it’s best to see the kinds of sequence generators that make interesting examples.
### 11.1 Sequence Constructors The [in-range](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=sequences.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._in-range%2529%2529&version=8.18.0.13) function generates a sequence of numbers, given an optional starting number (which defaults to 0), a number before which the sequence ends, and an optional step (which defaults to 1). Using a non-negative integer k directly as a sequence is a shorthand for ([in-range](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=sequences.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._in-range%2529%2529&version=8.18.0.13) k). Examples: > ```racket > > ( for ( [ i 3 ] ) ( display i ) ) > 012 > > ( for ( [ i ( in-range 3 ) ] ) ( display i ) ) > 012 > > ( for ( [ i ( in-range 1 4 ) ] ) ( display i ) ) > 123 > > ( for ( [ i ( in-range 1 4 2 ) ] ) ( display i ) ) > 13 > > ( for ( [ i ( in-range 4 1 -1 ) ] ) ( display i ) ) > 432 > > ( for ( [ i ( in-range 1 4 1/2 ) ] ) ( printf " ~a " i ) ) > 1 3/2 2 5/2 3 7/2 > ```
### 11.1 Sequence Constructors The [in-naturals](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=sequences.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._in-naturals%2529%2529&version=8.18.0.13) function is similar, except that the starting number must be an exact non-negative integer (which defaults to 0), the step is always 1, and there is no upper limit. A [for](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=for.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._for%2529%2529&version=8.18.0.13) loop using just [in-naturals](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=sequences.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._in-naturals%2529%2529&version=8.18.0.13) will never terminate unless a body expression raises an exception or otherwise escapes. Example: > ```racket > > ( for ( [ i ( in-naturals ) ] ) ( if ( = i 10 ) ( error "too much!" ) ( display i ) ) ) > 0123456789 > too much! > ```
### 11.1 Sequence Constructors The [stop-before](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=sequences.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._stop-before%2529%2529&version=8.18.0.13) and [stop-after](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=sequences.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._stop-after%2529%2529&version=8.18.0.13) functions construct a new sequence given a sequence and a predicate. The new sequence is like the given sequence, but truncated either immediately before or immediately after the first element for which the predicate returns true. Example: > ```racket > > ( for ( [ i ( stop-before "abc def" char-whitespace? ) ] ) ( display i ) ) > abc > ```
### 11.1 Sequence Constructors Sequence constructors like [in-list](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=sequences.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._in-list%2529%2529&version=8.18.0.13), [in-vector](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=sequences.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._in-vector%2529%2529&version=8.18.0.13) and [in-string](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=sequences.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._in-string%2529%2529&version=8.18.0.13) simply make explicit the use of a list, vector, or string as a sequence. Along with [in-range](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=sequences.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._in-range%2529%2529&version=8.18.0.13), these constructors raise an exception when given the wrong kind of value, and since they otherwise avoid a run-time dispatch to determine the sequence type, they enable more efficient code generation; see [Iteration Performance](#%28part._for-performance%29) for more information. Examples:
### 11.1 Sequence Constructors > ```racket > > ( for ( [ i ( in-string "abc" ) ] ) ( display i ) ) > abc > > ( for ( [ i ( in-string ' ( 1 2 3 ) ) ] ) ( display i ) ) > in-string: contract violation > expected: string? > given: '(1 2 3) > ``` > > > <img src="magnify.png" width="24" height="24" alt="+" />[Sequences](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=sequences.html&version=8.18.0.13) in [The Racket Reference](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=index.html&version=8.18.0.13) provides more on sequences.
### 11.2 [for](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=for.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._for%2529%2529&version=8.18.0.13) and [for*](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=for.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._for%252A%2529%2529&version=8.18.0.13) A more complete syntax of [for](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=for.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._for%2529%2529&version=8.18.0.13) is > > ``` (for (clause ...) > > body ...+ ) clause   =   [id sequence-expr]     |   #:when boolean-expr     |   #:unless boolean-expr
### 11.2 [for](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=for.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._for%2529%2529&version=8.18.0.13) and [for*](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=for.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._for%252A%2529%2529&version=8.18.0.13) ``` When multiple \[id sequence-expr\] clauses are provided in a for form, the corresponding sequences are traversed in parallel: > ```racket > > ( for ( [ i ( in-range 1 4 ) ] [ chapter ' ( "Intro" "Details" "Conclusion" ) ] ) ( printf "Chapter ~a. ~a\n" i chapter ) ) > Chapter 1. Intro Chapter 2. Details Chapter 3. Conclusion > ``` With parallel sequences, the for expression stops iterating when any sequence ends. This behavior allows in-naturals, which creates an infinite sequence of numbers, to be used for indexing: > ```racket > > ( for ( [ i ( in-naturals 1 ) ] [ chapter ' ( "Intro" "Details" "Conclusion" ) ] ) ( printf "Chapter ~a. ~a\n" i chapter ) ) > Chapter 1. Intro Chapter 2. Details Chapter 3. Conclusion > ``` The for* form, which has the same syntax as for, nests multiple sequences instead of running them in parallel: > ```racket > > ( for* ( [ book ' ( "Guide" "Reference" ) ] [ chapter ' ( "Intro" "Details" "Conclusion" ) ] ) ( printf "~a ~a\n" book chapter ) ) > Guide Intro Guide Details Guide Conclusion Reference Intro Reference Details Reference Conclusion > ``` Thus, for* is a shorthand for nested fors in the same way that let* is a shorthand for nested lets. The #:when boolean-expr form of a clause is another shorthand. It allows the bodys to evaluate only when the boolean-expr produces a true value: > ```racket > > ( for* ( [ book ' ( "Guide" "Reference" ) ] [ chapter ' ( "Intro" "Details" "Conclusion" ) ] #:when ( not ( equal? chapter "Details" ) ) ) ( printf "~a ~a\n" book chapter ) ) > Guide Intro Guide Conclusion Reference Intro Reference Conclusion > ``` A boolean-expr with #:when can refer to any of the preceding iteration bindings. In a for form, this scoping makes sense only if the test is nested in the iteration of the preceding bindings; thus, bindings separated by #:when are mutually nested, instead of in parallel, even with for. > ```racket > > ( for ( [ book ' ( "Guide" "Reference" "Notes" ) ] #:when ( not ( equal? book "Notes" ) ) [ i ( in-naturals 1 ) ] [ chapter ' ( "Intro" "Details" "Conclusion" "Index" ) ] #:when ( not ( equal? chapter "Index" ) ) ) ( printf "~a Chapter ~a. ~a\n" book i chapter ) ) > Guide Chapter 1. Intro Guide Chapter 2. Details Guide Chapter 3. Conclusion Reference Chapter 1. Intro Reference Chapter 2. Details Reference Chapter 3. Conclusion > ``` An #:unless clause is analogous to a #:when clause, but the bodys evaluate only when the boolean-expr produces a false value. ### 11.3 for/list and for*/list The for/list form, which has the same syntax as for, evaluates the bodys to obtain values that go into a newly constructed list: > ```racket > > ( for/list ( [ i ( in-naturals 1 ) ] [ chapter ' ( "Intro" "Details" "Conclusion" ) ] ) ( string-append ( number → string i ) ". " chapter ) ) > '("1. Intro" "2. Details" "3. Conclusion") > ``` A #:when clause in a for-list form prunes the result list along with evaluations of the bodys: > ```racket > > ( for/list ( [ i ( in-naturals 1 ) ] [ chapter ' ( "Intro" "Details" "Conclusion" ) ] #:when ( odd? i ) ) chapter ) > '("Intro" "Conclusion") > ``` This pruning behavior of #:when is more useful with for/list than for. Whereas a plain when form normally suffices with for, a when expression form in a for/list would cause the result list to contain #<void>s instead of omitting list elements. The for*/list form is like for*, nesting multiple iterations: > ```racket > > ( for*/list ( [ book ' ( "Guide" "Ref." ) ] [ chapter ' ( "Intro" "Details" ) ] ) ( string-append book " " chapter ) ) > '("Guide Intro" "Guide Details" "Ref. Intro" "Ref. Details") > ``` A for*/list form is not quite the same thing as nested for/list forms. Nested for/lists would produce a list of lists, instead of one flattened list. Much like #:when, then, the nesting of for*/list is more useful than the nesting of for*. ### 11.4 for/vector and for*/vector The for/vector form can be used with the same syntax as the for/list form, but the evaluated bodys go into a newly-constructed vector instead of a list: > ```racket > > ( for/vector ( [ i ( in-naturals 1 ) ] [ chapter ' ( "Intro" "Details" "Conclusion" ) ] ) ( string-append ( number → string i ) ". " chapter ) ) > '#("1. Intro" "2. Details" "3. Conclusion") > ``` The for*/vector form behaves similarly, but the iterations are nested as in for*. The for/vector and for*/vector forms also allow the length of the vector to be constructed to be supplied in advance. The resulting iteration can be performed more efficiently than plain for/vector or for*/vector: > ```racket > > ( let ( [ chapters ' ( "Intro" "Details" "Conclusion" ) ] ) ( for/vector #:length ( length chapters ) ( [ i ( in-naturals 1 ) ] [ chapter chapters ] ) ( string-append ( number → string i ) ". " chapter ) ) ) > '#("1. Intro" "2. Details" "3. Conclusion") > ``` If a length is provided, the iteration stops when the vector is filled or the requested iterations are complete, whichever comes first. If the provided length exceeds the requested number of iterations, then the remaining slots in the vector are initialized to the default argument of make-vector. ### 11.5 for/and and for/or The for/and form combines iteration results with and, stopping as soon as it encounters #f: > ```racket > > ( for/and ( [ chapter ' ( "Intro" "Details" "Conclusion" ) ] ) ( equal? chapter "Intro" ) ) > #f > ``` The for/or form combines iteration results with or, stopping as soon as it encounters a true value: > ```racket > > ( for/or ( [ chapter ' ( "Intro" "Details" "Conclusion" ) ] ) ( equal? chapter "Intro" ) ) > #t > ``` As usual, the for*/and and for*/or forms provide the same facility with nested iterations. ### 11.6 for/first and for/last The for/first form returns the result of the first time that the bodys are evaluated, skipping further iterations. This form is most useful with a #:when clause. > ```racket > > ( for/first ( [ chapter ' ( "Intro" "Details" "Conclusion" "Index" ) ] #:when ( not ( equal? chapter "Intro" ) ) ) chapter ) > "Details" > ``` If the bodys are evaluated zero times, then the result is #f. The for/last form runs all iterations, returning the value of the last iteration (or #f if no iterations are run): > ```racket > > ( for/last ( [ chapter ' ( "Intro" "Details" "Conclusion" "Index" ) ] #:when ( not ( equal? chapter "Index" ) ) ) chapter ) > "Conclusion" > ``` As usual, the for*/first and for*/last forms provide the same facility with nested iterations: > ```racket > > ( for*/first ( [ book ' ( "Guide" "Reference" ) ] [ chapter ' ( "Intro" "Details" "Conclusion" "Index" ) ] #:when ( not ( equal? chapter "Intro" ) ) ) ( list book chapter ) ) > '("Guide" "Details") > > ( for*/last ( [ book ' ( "Guide" "Reference" ) ] [ chapter ' ( "Intro" "Details" "Conclusion" "Index" ) ] #:when ( not ( equal? chapter "Index" ) ) ) ( list book chapter ) ) > '("Reference" "Conclusion") > ``` ### 11.7 for/fold and for*/fold The for/fold form is a very general way to combine iteration results. Its syntax is slightly different than the syntax of for, because accumulation variables must be declared at the beginning: > ```racket > ( for/fold ( [ accum-id init-expr ] ... ) > ( clause ... ) > body ...+ ) > ``` In the simple case, only one \[accum-id init-expr\] is provided, and the result of the for/fold is the final value for accum-id, which starts out with the value of init-expr. In the clauses and bodys, accum-id can be referenced to get its current value, and the last body provides the value of accum-id for the next iteration. Examples: > ```racket > > ( for/fold ( [ len 0 ] ) ( [ chapter ' ( "Intro" "Conclusion" ) ] ) ( + len ( string-length chapter ) ) ) > 15 > > ( for/fold ( [ prev #f ] ) ( [ i ( in-naturals 1 ) ] [ chapter ' ( "Intro" "Details" "Details" "Conclusion" ) ] #:when ( not ( equal? chapter prev ) ) ) ( printf "~a. ~a\n" i chapter ) chapter ) > 1. Intro 2. Details 4. Conclusion > "Conclusion" > ``` When multiple accum-ids are specified, then the last body must produce multiple values, one for each accum-id. The for/fold expression itself produces multiple values for the results. Example: > ```racket > > ( for/fold ( [ prev #f ] [ counter 1 ] ) ( [ chapter ' ( "Intro" "Details" "Details" "Conclusion" ) ] #:when ( not ( equal? chapter prev ) ) ) ( printf "~a. ~a\n" counter chapter ) ( values chapter ( add1 counter ) ) ) > 1. Intro 2. Details 3. Conclusion > "Conclusion" 4 > ``` ### 11.8 Multiple-Valued Sequences In the same way that a function or expression can produce multiple values, individual iterations of a sequence can produce multiple elements. For example, a hash table as a sequence generates two values for each iteration: a key and a value. In the same way that let-values binds multiple results to multiple identifiers, for can bind multiple sequence elements to multiple iteration identifiers: > > > While let must be changed to let-values to bind multiple identifiers, for simply allows a parenthesized list of identifiers instead of a single identifier in any clause. > ```racket > > ( for ( [ ( k v ) #hash ( ( "apple" . 1 ) ( "banana" . 3 ) ) ] ) ( printf "~a count: ~a\n" k v ) ) > apple count: 1 banana count: 3 > ``` This extension to multiple-value bindings works for all for variants. For example, for*/list nests iterations, builds a list, and also works with multiple-valued sequences: > ```racket > > ( for*/list ( [ ( k v ) #hash ( ( "apple" . 1 ) ( "banana" . 3 ) ) ] [ ( i ) ( in-range v ) ] ) k ) > '("apple" "banana" "banana" "banana") > ``` ### 11.9 Breaking an Iteration An even more complete syntax of for is > > ``` (for (clause ...) > > body-or-break ... body )   clause   =   [id sequence-expr]     |   #:when boolean-expr     |   #:unless boolean-expr     |   break           body-or-break   =   body     |   break           break   =   #:break boolean-expr     |   #:final boolean-expr``` That is, a #:break or #:final clause can be included among the binding clauses and body of the iteration. Among the binding clauses, #:break is like #:unless but when its boolean-expr is true, all sequences within the [for](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=for.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._for%2529%2529&version=8.18.0.13) are stopped. Among the bodys, #:break has the same effect on sequences when its boolean-expr is true, and it also prevents later bodys from evaluation in the current iteration. For example, while using #:unless between clauses effectively skips later sequences as well as the body, > ```racket > > ( for ( [ book ' ( "Guide" "Story" "Reference" ) ] #:unless ( equal? book "Story" ) [ chapter ' ( "Intro" "Details" "Conclusion" ) ] ) ( printf "~a ~a\n" book chapter ) ) > Guide Intro Guide Details Guide Conclusion Reference Intro Reference Details Reference Conclusion > ``` using #:break causes the entire [for](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=for.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._for%2529%2529&version=8.18.0.13) iteration to terminate: > ```racket > > ( for ( [ book ' ( "Guide" "Story" "Reference" ) ] #:break ( equal? book "Story" ) [ chapter ' ( "Intro" "Details" "Conclusion" ) ] ) ( printf "~a ~a\n" book chapter ) ) > Guide Intro Guide Details Guide Conclusion > > ( for* ( [ book ' ( "Guide" "Story" "Reference" ) ] [ chapter ' ( "Intro" "Details" "Conclusion" ) ] ) #:break ( and ( equal? book "Story" ) ( equal? chapter "Conclusion" ) ) ( printf "~a ~a\n" book chapter ) ) > Guide Intro Guide Details Guide Conclusion Story Intro Story Details > ``` A #:final clause is similar to #:break, but it does not immediately terminate the iteration. Instead, it allows at most one more element to be drawn for each sequence and at most one more evaluation of the bodys. > ```racket > > ( for* ( [ book ' ( "Guide" "Story" "Reference" ) ] [ chapter ' ( "Intro" "Details" "Conclusion" ) ] ) #:final ( and ( equal? book "Story" ) ( equal? chapter "Conclusion" ) ) ( printf "~a ~a\n" book chapter ) ) > Guide Intro Guide Details Guide Conclusion Story Intro Story Details Story Conclusion > > ( for ( [ book ' ( "Guide" "Story" "Reference" ) ] #:final ( equal? book "Story" ) [ chapter ' ( "Intro" "Details" "Conclusion" ) ] ) ( printf "~a ~a\n" book chapter ) ) > Guide Intro Guide Details Guide Conclusion Story Intro > ``` ### 11.10 Iteration Performance Ideally, a [for](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=for.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._for%2529%2529&version=8.18.0.13) iteration should run as fast as a loop that you write by hand as a recursive-function invocation. A hand-written loop, however, is normally specific to a particular kind of data, such as lists. In that case, the hand-written loop uses selectors like [car](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=pairs.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._car%2529%2529&version=8.18.0.13) and [cdr](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=pairs.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._cdr%2529%2529&version=8.18.0.13) directly, instead of handling all forms of sequences and dispatching to an appropriate iterator. The [for](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=for.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._for%2529%2529&version=8.18.0.13) forms can provide the performance of hand-written loops when enough information is apparent about the sequences to iterate, specifically when the clause has one of the following fast-clause forms: | | | | | | |--------------:|:----|:---:|:----|:-------------------------------| |   fast-clause |   | = |   | \[id fast-seq\] | |   |   | \| |   | \[(id) fast-seq\] | |   |   | \| |   | \[(id id) fast-indexed-seq\] | |   |   | \| |   | \[(id ...) fast-parallel-seq\] | | | | | | | |-----------:|:----|:---:|:----|:----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| |   fast-seq |   | = |   | literal | |   |   | \| |   | ([in-range](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=sequences.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._in-range%2529%2529&version=8.18.0.13) expr) | |   |   | \| |   | ([in-range](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=sequences.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._in-range%2529%2529&version=8.18.0.13) expr expr) | |   |   | \| |   | ([in-range](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=sequences.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._in-range%2529%2529&version=8.18.0.13) expr expr expr) | |   |   | \| |   | ([in-inclusive-range](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=sequences.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._in-inclusive-range%2529%2529&version=8.18.0.13) expr expr) | |   |   | \| |   | ([in-inclusive-range](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=sequences.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._in-inclusive-range%2529%2529&version=8.18.0.13) expr expr expr) | |   |   | \| |   | ([in-naturals](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=sequences.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._in-naturals%2529%2529&version=8.18.0.13)) | |   |   | \| |   | ([in-naturals](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=sequences.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._in-naturals%2529%2529&version=8.18.0.13) expr) | |   |   | \| |   | ([in-list](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=sequences.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._in-list%2529%2529&version=8.18.0.13) expr) | |   |   | \| |   | ([in-mlist](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=sequences.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._in-mlist%2529%2529&version=8.18.0.13) expr) | |   |   | \| |   | ([in-vector](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=sequences.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._in-vector%2529%2529&version=8.18.0.13) expr) | |   |   | \| |   | ([in-string](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=sequences.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._in-string%2529%2529&version=8.18.0.13) expr) | |   |   | \| |   | ([in-bytes](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=sequences.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._in-bytes%2529%2529&version=8.18.0.13) expr) | |   |   | \| |   | ([in-value](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=sequences.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._in-value%2529%2529&version=8.18.0.13) expr) | |   |   | \| |   | ([stop-before](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=sequences.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._stop-before%2529%2529&version=8.18.0.13) fast-seq predicate-expr) | |   |   | \| |   | ([stop-after](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=sequences.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._stop-after%2529%2529&version=8.18.0.13) fast-seq predicate-expr) | | | | | | | |-------------------:|:----|:---:|:----|:-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| |   fast-indexed-seq |   | = |   | ([in-indexed](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=sequences.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._in-indexed%2529%2529&version=8.18.0.13) fast-seq) | |   |   | \| |   | ([stop-before](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=sequences.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._stop-before%2529%2529&version=8.18.0.13) fast-indexed-seq predicate-expr) | |   |   | \| |   | ([stop-after](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=sequences.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._stop-after%2529%2529&version=8.18.0.13) fast-indexed-seq predicate-expr) | | | | | | | |--------------------:|:----|:---:|:----|:--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| |   fast-parallel-seq |   | = |   | ([in-parallel](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=sequences.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._in-parallel%2529%2529&version=8.18.0.13) fast-seq ...) | |   |   | \| |   | ([stop-before](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=sequences.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._stop-before%2529%2529&version=8.18.0.13) fast-parallel-seq predicate-expr) | |   |   | \| |   | ([stop-after](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=sequences.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._stop-after%2529%2529&version=8.18.0.13) fast-parallel-seq predicate-expr) | Examples: > ```racket > > ( define lst ' ( a b c d e f g h ) ) > > ( time ( for ( [ i ( in-range 100000 ) ] ) ( for ( [ elem ( in-list lst ) ] ) ; fast ( void ) ) ) ) > cpu time: 7 real time: 1 gc time: 0 > > ( time ( for ( [ i ( in-range 100000 ) ] ) ( for ( [ elem ' ( a b c d e f g h ) ] ) ; also fast ( void ) ) ) ) > cpu time: 7 real time: 1 gc time: 0 > > ( time ( for ( [ i ( in-range 100000 ) ] ) ( for ( [ elem lst ] ) ; slower ( void ) ) ) ) > cpu time: 27 real time: 4 gc time: 0 > > ( time ( let ( [ seq ( in-list lst ) ] ) ( for ( [ i ( in-range 100000 ) ] ) ( for ( [ elem seq ] ) ; also slower ( void ) ) ) ) ) > cpu time: 53 real time: 13 gc time: 9 > ``` The grammars above are not complete, because the set of syntactic patterns that provide good performance is extensible, just like the set of sequence values. The documentation for a sequence constructor should indicate the performance benefits of using it directly in a [for](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=for.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._for%2529%2529&version=8.18.0.13) clause. > > > <img src="magnify.png" width="24" height="24" alt="+" />[Iterations and Comprehensions: for, for/list, ...](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=for.html&version=8.18.0.13) in [The Racket Reference](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=index.html&version=8.18.0.13) provides more on iterations and comprehensions. ------------------------------------------------------------------------ # 12 Pattern Matching ## 12 Pattern Matching > > > ([require](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._require%2529%2529&version=8.18.0.13) racket/match) is needed for [#lang](Module_Syntax.html#%28part._hash-lang%29) [racket/base](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=index.html&version=8.18.0.13). The [match](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=match.html%23%2528form._%2528%2528lib._racket%252Fmatch..rkt%2529._match%2529%2529&version=8.18.0.13) form supports pattern matching on arbitrary Racket values, as opposed to functions like [regexp-match](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=regexp.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._regexp-match%2529%2529&version=8.18.0.13) that compare regular expressions to byte and character sequences (see [Regular Expressions](regexp.html)). > > ``` (match target-expr > > [ pattern expr ...+ ] ... ) ```
### 11.2 [for](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=for.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._for%2529%2529&version=8.18.0.13) and [for*](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=for.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._for%252A%2529%2529&version=8.18.0.13) (1) →``` The grow method in picky-fish% is declared with [define/override](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=createclass.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fclass-internal..rkt%2529._define%252Foverride%2529%2529&version=8.18.0.13) instead of [define/public](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=createclass.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fclass-internal..rkt%2529._define%252Fpublic%2529%2529&version=8.18.0.13), because grow is meant as an overriding declaration. If grow had been declared with [define/public](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=createclass.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fclass-internal..rkt%2529._define%252Fpublic%2529%2529&version=8.18.0.13), an error would have been signaled when evaluating the [class](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=createclass.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fclass-internal..rkt%2529._class%2529%2529&version=8.18.0.13) expression, because fish% already supplies grow.
### 11.2 [for](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=for.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._for%2529%2529&version=8.18.0.13) and [for*](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=for.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._for%252A%2529%2529&version=8.18.0.13) Using [define/override](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=createclass.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fclass-internal..rkt%2529._define%252Foverride%2529%2529&version=8.18.0.13) also allows the invocation of the overridden method via a [super](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=createclass.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fclass-internal..rkt%2529._super%2529%2529&version=8.18.0.13) call. For example, the grow implementation in picky-fish% uses [super](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=createclass.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fclass-internal..rkt%2529._super%2529%2529&version=8.18.0.13) to delegate to the superclass implementation.
### 13.2 Initialization Arguments Since picky-fish% declares no initialization arguments, any initialization values supplied in ([new](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=objcreation.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fclass-internal..rkt%2529._new%2529%2529&version=8.18.0.13) picky-fish% ....) are propagated to the superclass initialization, i.e., to fish%. A subclass can supply additional initialization arguments for its superclass in a [super-new](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=objcreation.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fclass-internal..rkt%2529._super-new%2529%2529&version=8.18.0.13) call, and such initialization arguments take precedence over arguments supplied to [new](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=objcreation.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fclass-internal..rkt%2529._new%2529%2529&version=8.18.0.13). For example, the following size-10-fish% class always generates fish of size 10:
### 13.2 Initialization Arguments > <table data-cellpadding="0" data-cellspacing="0"><colgroup><col style="width: 100%" /></colgroup><tbody><tr><td>([define](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=define.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._define%2529%2529&version=8.18.0.13) size-10-fish% ([class](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=createclass.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fclass-internal..rkt%2529._class%2529%2529&version=8.18.0.13) fish% ([super-new](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=objcreation.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fclass-internal..rkt%2529._super-new%2529%2529&version=8.18.0.13) [size 10])))</td></tr><tr><td><p> </p></td></tr><tr><td><pre><code>&gt; ( send ( new size-10-fish% ) get-size ) > 10</code></pre></td></tr></tbody></table>
### 13.2 Initialization Arguments In the case of size-10-fish%, supplying a size initialization argument with [new](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=objcreation.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fclass-internal..rkt%2529._new%2529%2529&version=8.18.0.13) would result in an initialization error; because the size in [super-new](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=objcreation.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fclass-internal..rkt%2529._super-new%2529%2529&version=8.18.0.13) takes precedence, a size supplied to [new](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=objcreation.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fclass-internal..rkt%2529._new%2529%2529&version=8.18.0.13) would have no target declaration. An initialization argument is optional if the [class](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=createclass.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fclass-internal..rkt%2529._class%2529%2529&version=8.18.0.13) form declares a default value. For example, the following default-10-fish% class accepts a size initialization argument, but its value defaults to 10 if no value is supplied on instantiation: > ``` (define default-10-fish% (class fish% > ( init [ size 10 ] ) > ( super-new [ size size ] ) ) )
### 13.2 Initialization Arguments > ( new default-10-fish% ) > (object:default-10-fish% ...) > > ( new default-10-fish% [ size 20 ] ) > (object:default-10-fish% ...) ``` (implied) →``` The first set of interface-exprs determines the domain of the mixin, and the second set determines the range. That is, the expansion is a function that tests whether a given base class implements the first sequence of interface-exprs and produces a class that implements the second sequence of interface-exprs. Other requirements, such as the presence of [inherit](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=createclass.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fclass-internal..rkt%2529._inherit%2529%2529&version=8.18.0.13)ed methods in the superclass, are then checked for the [class](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=createclass.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fclass-internal..rkt%2529._class%2529%2529&version=8.18.0.13) expansion of the [mixin](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=mixins.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fclass-internal..rkt%2529._mixin%2529%2529&version=8.18.0.13) form. For example: > ```racket > > ( define choosy-interface ( interface ( ) choose? ) ) > > ( define hungry-interface ( interface ( ) eat ) ) > > ( define choosy-eater-mixin ( mixin ( choosy-interface ) ( hungry-interface ) ( inherit choose? ) ( super-new ) ( define/public ( eat x ) ( cond [ ( choose? x ) ( printf "chomp chomp chomp on ~a.\n" x ) ] [ else ( printf "I'm not crazy about ~a.\n" x ) ] ) ) ) ) > > ( define herring-lover% ( class* object% ( choosy-interface ) ( super-new ) ( define/public ( choose? x ) ( regexp-match #px"^herring" x ) ) ) ) > > ( define herring-eater% ( choosy-eater-mixin herring-lover% ) ) > > ( define eater ( new herring-eater% ) ) > > ( send eater eat "elderberry" ) > I'm not crazy about elderberry. > > ( send eater eat "herring" ) > chomp chomp chomp on herring. > > ( send eater eat "herring ice cream" ) > chomp chomp chomp on herring ice cream. > ``` Mixins not only override methods and introduce public methods, they can also augment methods, introduce augment-only methods, add an overrideable augmentation, and add an augmentable override — all of the things that a class can do (see [Final, Augment, and Inner](#%28part._inner%29)). #### 13.7.3 Parameterized Mixins As noted in [Controlling the Scope of External Names](#%28part._extnames%29), external names can be bound with [define-member-name](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=createclass.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fclass-internal..rkt%2529._define-member-name%2529%2529&version=8.18.0.13). This facility allows a mixin to be generalized with respect to the methods that it defines and uses. For example, we can parameterize hungry-mixin with respect to the external member key for eat: > ```racket > ( define ( make-hungry-mixin eat-method-key ) > ( define-member-name eat eat-method-key ) > ( mixin ( ) ( ) ( super-new ) > ( inherit eat ) > ( define/public ( eat-more x y ) ( eat x ) ( eat y ) ) ) ) > ``` To obtain a particular hungry-mixin, we must apply this function to a member key that refers to a suitable eat method, which we can obtain using [member-name-key](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=createclass.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fclass-internal..rkt%2529._member-name-key%2529%2529&version=8.18.0.13): > ```racket > ( ( make-hungry-mixin ( member-name-key eat ) ) > ( class object% .... ( define/public ( eat x ) ' yum ) ) ) > ``` Above, we apply hungry-mixin to an anonymous class that provides eat, but we can also combine it with a class that provides chomp, instead: > ```racket > ( ( make-hungry-mixin ( member-name-key chomp ) ) > ( class object% .... ( define/public ( chomp x ) ' yum ) ) ) > ``` ### 13.8 Traits A trait is similar to a mixin, in that it encapsulates a set of methods to be added to a class. A trait is different from a mixin in that its individual methods can be manipulated with trait operators such as [trait-sum](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=trait.html%23%2528def._%2528%2528lib._racket%252Ftrait..rkt%2529._trait-sum%2529%2529&version=8.18.0.13) (merge the methods of two traits), [trait-exclude](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=trait.html%23%2528form._%2528%2528lib._racket%252Ftrait..rkt%2529._trait-exclude%2529%2529&version=8.18.0.13) (remove a method from a trait), and [trait-alias](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=trait.html%23%2528form._%2528%2528lib._racket%252Ftrait..rkt%2529._trait-alias%2529%2529&version=8.18.0.13) (add a copy of a method with a new name; do not redirect any calls to the old name). The practical difference between mixins and traits is that two traits can be combined, even if they include a common method and even if neither method can sensibly override the other. In that case, the programmer must explicitly resolve the collision, usually by aliasing methods, excluding methods, and merging a new trait that uses the aliases. Suppose our fish% programmer wants to define two class extensions, spots and stripes, each of which includes a get-color method. The fish’s spot color should not override the stripe color nor vice versa; instead, a spots+stripes-fish% should combine the two colors, which is not possible if spots and stripes are implemented as plain mixins. If, however, spots and stripes are implemented as traits, they can be combined. First, we alias get-color in each trait to a non-conflicting name. Second, the get-color methods are removed from both and the traits with only aliases are merged. Finally, the new trait is used to create a class that introduces its own get-color method based on the two aliases, producing the desired spots+stripes extension. #### 13.8.1 Traits as Sets of Mixins One natural approach to implementing traits in Racket is as a set of mixins, with one mixin per trait method. For example, we might attempt to define the spots and stripes traits as follows, using association lists to represent sets: > ```racket > ( define spots-trait > ( list ( cons ' get-color > ( lambda ( % ) ( class % ( super-new ) > ( define/public ( get-color ) > ' black ) ) ) ) ) ) > ( define stripes-trait > ( list ( cons ' get-color > ( lambda ( % ) ( class % ( super-new ) > ( define/public ( get-color ) > ' red ) ) ) ) ) ) > ``` A set representation, such as the above, allows [trait-sum](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=trait.html%23%2528def._%2528%2528lib._racket%252Ftrait..rkt%2529._trait-sum%2529%2529&version=8.18.0.13) and [trait-exclude](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=trait.html%23%2528form._%2528%2528lib._racket%252Ftrait..rkt%2529._trait-exclude%2529%2529&version=8.18.0.13) as simple manipulations; unfortunately, it does not support the [trait-alias](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=trait.html%23%2528form._%2528%2528lib._racket%252Ftrait..rkt%2529._trait-alias%2529%2529&version=8.18.0.13) operator. Although a mixin can be duplicated in the association list, the mixin has a fixed method name, e.g., get-color, and mixins do not support a method-rename operation. To support [trait-alias](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=trait.html%23%2528form._%2528%2528lib._racket%252Ftrait..rkt%2529._trait-alias%2529%2529&version=8.18.0.13), we must parameterize the mixins over the external method name in the same way that eat was parameterized in [Parameterized Mixins](#%28part._parammixins%29). To support the [trait-alias](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=trait.html%23%2528form._%2528%2528lib._racket%252Ftrait..rkt%2529._trait-alias%2529%2529&version=8.18.0.13) operation, spots-trait should be represented as: > ```racket > ( define spots-trait > ( list ( cons ( member-name-key get-color ) > ( lambda ( get-color-key % ) > ( define-member-name get-color get-color-key ) > ( class % ( super-new ) > ( define/public ( get-color ) ' black ) ) ) ) ) ) > ``` When the get-color method in spots-trait is aliased to get-trait-color and the get-color method is removed, the resulting trait is the same as > ```racket > ( list ( cons ( member-name-key get-trait-color ) > ( lambda ( get-color-key % ) > ( define-member-name get-color get-color-key ) > ( class % ( super-new ) > ( define/public ( get-color ) ' black ) ) ) ) ) > ``` To apply a trait T to a class C and obtain a derived class, we use (([trait->mixin](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=trait.html%23%2528def._%2528%2528lib._racket%252Ftrait..rkt%2529._trait-%7E3emixin%2529%2529&version=8.18.0.13) T) C). The [trait->mixin](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=trait.html%23%2528def._%2528%2528lib._racket%252Ftrait..rkt%2529._trait-%7E3emixin%2529%2529&version=8.18.0.13) function supplies each mixin of T with the key for the mixin’s method and a partial extension of C: > ```racket > ( define ( ( trait->mixin T ) C ) > ( foldr ( lambda ( m % ) ( ( cdr m ) ( car m ) % ) ) C T ) ) > ``` Thus, when the trait above is combined with other traits and then applied to a class, the use of get-color becomes a reference to the external name get-trait-color. #### 13.8.2 Inherit and Super in Traits This first implementation of traits supports [trait-alias](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=trait.html%23%2528form._%2528%2528lib._racket%252Ftrait..rkt%2529._trait-alias%2529%2529&version=8.18.0.13), and it supports a trait method that calls itself, but it does not support trait methods that call each other. In particular, suppose that a spot-fish’s market value depends on the color of its spots: > ```racket > ( define spots-trait > ( list ( cons ( member-name-key get-color ) .... ) > ( cons ( member-name-key get-price ) > ( lambda ( get-price % ) .... > ( class % .... > ( define/public ( get-price ) > .... ( get-color ) .... ) ) ) ) ) ) > ``` In this case, the definition of spots-trait fails, because get-color is not in scope for the get-price mixin. Indeed, depending on the order of mixin application when the trait is applied to a class, the get-color method may not be available when get-price mixin is applied to the class. Therefore adding an ([inherit](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=createclass.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fclass-internal..rkt%2529._inherit%2529%2529&version=8.18.0.13) get-color) declaration to the get-price mixin does not solve the problem. One solution is to require the use of ([send](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=ivaraccess.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fclass-internal..rkt%2529._send%2529%2529&version=8.18.0.13) [this](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=createclass.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fclass-internal..rkt%2529._this%2529%2529&version=8.18.0.13) get-color) in methods such as get-price. This change works because [send](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=ivaraccess.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fclass-internal..rkt%2529._send%2529%2529&version=8.18.0.13) always delays the method lookup until the method call is evaluated. The delayed lookup is more expensive than a direct call, however. Worse, it also delays checking whether a get-color method even exists. A second, effective, and efficient solution is to change the encoding of traits. Specifically, we represent each method as a pair of mixins: one that introduces the method and one that implements it. When a trait is applied to a class, all of the method-introducing mixins are applied first. Then the method-implementing mixins can use [inherit](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=createclass.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fclass-internal..rkt%2529._inherit%2529%2529&version=8.18.0.13) to directly access any introduced method. > ```racket > ( define spots-trait > ( list ( list ( local-member-name-key get-color ) > ( lambda ( get-color get-price % ) .... > ( class % .... > ( define/public ( get-color ) ( void ) ) ) ) > ( lambda ( get-color get-price % ) .... > ( class % .... > ( define/override ( get-color ) ' black ) ) ) ) > ( list ( local-member-name-key get-price ) > ( lambda ( get-color get-price % ) .... > ( class % .... > ( define/public ( get-price ) ( void ) ) ) ) > ( lambda ( get-color get-price % ) .... > ( class % .... > ( inherit get-color ) > ( define/override ( get-price ) > .... ( get-color ) .... ) ) ) ) ) ) > ``` With this trait encoding, [trait-alias](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=trait.html%23%2528form._%2528%2528lib._racket%252Ftrait..rkt%2529._trait-alias%2529%2529&version=8.18.0.13) adds a new method with a new name, but it does not change any references to the old method. #### 13.8.3 The [trait](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=trait.html%23%2528form._%2528%2528lib._racket%252Ftrait..rkt%2529._trait%2529%2529&version=8.18.0.13) Form > > > ([require](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._require%2529%2529&version=8.18.0.13) racket/trait) is needed. The general-purpose trait pattern is clearly too complex for a programmer to use directly, but it is easily codified in a [trait](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=trait.html%23%2528form._%2528%2528lib._racket%252Ftrait..rkt%2529._trait%2529%2529&version=8.18.0.13) macro: > > | | > > |---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| > > | ([trait](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=trait.html%23%2528form._%2528%2528lib._racket%252Ftrait..rkt%2529._trait%2529%2529&version=8.18.0.13) trait-clause ...) | The ids in the optional [inherit](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=createclass.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fclass-internal..rkt%2529._inherit%2529%2529&version=8.18.0.13) clause are available for direct reference in the method exprs, and they must be supplied either by other traits or the base class to which the trait is ultimately applied. Using this form in conjunction with trait operators such as [trait-sum](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=trait.html%23%2528def._%2528%2528lib._racket%252Ftrait..rkt%2529._trait-sum%2529%2529&version=8.18.0.13), [trait-exclude](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=trait.html%23%2528form._%2528%2528lib._racket%252Ftrait..rkt%2529._trait-exclude%2529%2529&version=8.18.0.13), [trait-alias](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=trait.html%23%2528form._%2528%2528lib._racket%252Ftrait..rkt%2529._trait-alias%2529%2529&version=8.18.0.13), and [trait->mixin](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=trait.html%23%2528def._%2528%2528lib._racket%252Ftrait..rkt%2529._trait-%7E3emixin%2529%2529&version=8.18.0.13), we can implement spots-trait and stripes-trait as desired. > ```racket > ( define spots-trait > ( trait > ( define/public ( get-color ) ' black ) > ( define/public ( get-price ) ... ( get-color ) ... ) ) ) > ( define stripes-trait > ( trait > ( define/public ( get-color ) ' red ) ) ) > ( define spots+stripes-trait > ( trait-sum > ( trait-exclude ( trait-alias spots-trait > get-color get-spots-color ) > get-color ) > ( trait-exclude ( trait-alias stripes-trait > get-color get-stripes-color ) > get-color ) > ( trait > ( inherit get-spots-color get-stripes-color ) > ( define/public ( get-color ) > .... ( get-spots-color ) .... ( get-stripes-color ) .... ) ) ) ) > ``` ### 13.9 Class Contracts As classes are values, they can flow across contract boundaries, and we may wish to protect parts of a given class with contracts. For this, the [class/c](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Object_and_Class_Contracts.html%23%2528form._%2528%2528lib._racket%252Fclass..rkt%2529._class%252Fc%2529%2529&version=8.18.0.13) form is used. The [class/c](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Object_and_Class_Contracts.html%23%2528form._%2528%2528lib._racket%252Fclass..rkt%2529._class%252Fc%2529%2529&version=8.18.0.13) form has many subforms, which describe two types of contracts on fields and methods: those that affect uses via instantiated objects and those that affect subclasses. #### 13.9.1 External Class Contracts In its simplest form, [class/c](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Object_and_Class_Contracts.html%23%2528form._%2528%2528lib._racket%252Fclass..rkt%2529._class%252Fc%2529%2529&version=8.18.0.13) protects the public fields and methods of objects instantiated from the contracted class. There is also an [object/c](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Object_and_Class_Contracts.html%23%2528form._%2528%2528lib._racket%252Fclass..rkt%2529._object%252Fc%2529%2529&version=8.18.0.13) form that can be used to similarly protect the public fields and methods of a particular object. Take the following definition of animal%, which uses a public field for its size attribute: > ```racket > ( define animal% > ( class object% > ( super-new ) > ( field [ size 10 ] ) > ( define/public ( eat food ) > ( set! size ( + size ( get-field size food ) ) ) ) ) ) > ``` For any instantiated animal%, accessing the size field should return a positive number. Also, if the size field is set, it should be assigned a positive number. Finally, the eat method should receive an argument which is an object with a size field that contains a positive number. To ensure these conditions, we will define the animal% class with an appropriate contract: > ```racket > ( define positive/c ( and/c number? positive? ) ) > ( define edible/c ( object/c ( field [ size positive/c ] ) ) ) > ( define/contract animal% > ( class/c ( field [ size positive/c ] ) > [ eat ( -> m edible/c void? ) ] ) > ( class object% > ( super-new ) > ( field [ size 10 ] ) > ( define/public ( eat food ) > ( set! size ( + size ( get-field size food ) ) ) ) ) ) > ``` Here we use [->m](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Object_and_Class_Contracts.html%23%2528form._%2528%2528lib._racket%252Fclass..rkt%2529._-%7E3em%2529%2529&version=8.18.0.13) to describe the behavior of eat since we do not need to describe any requirements for the [this](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=createclass.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fclass-internal..rkt%2529._this%2529%2529&version=8.18.0.13) parameter. Now that we have our contracted class, we can see that the contracts on both size and eat are enforced: > ```racket > > ( define bob ( new animal% ) ) > > ( set-field! size bob 3 ) > > ( get-field size bob ) > 3 > > ( set-field! size bob ' large ) > animal%: contract violation > expected: positive/c > given: 'large > in: the size field in > (class/c > (eat > (->m > (object/c (field (size positive/c))) > void?)) > (field (size positive/c))) > contract from: (definition animal%) > blaming: top-level > (assuming the contract is correct) > at: eval:31:0 > > ( define richie ( new animal% ) ) > > ( send bob eat richie ) > > ( get-field size bob ) > 13 > > ( define rock ( new object% ) ) > > ( send bob eat rock ) > eat: contract violation; > no public field size > in: the 1st argument of > the eat method in > (class/c > (eat > (->m > (object/c (field (size positive/c))) > void?)) > (field (size positive/c))) > contract from: (definition animal%) > contract on: animal% > blaming: top-level > (assuming the contract is correct) > at: eval:31:0 > > ( define giant ( new ( class object% ( super-new ) ( field [ size ' large ] ) ) ) ) > > ( send bob eat giant ) > eat: contract violation > expected: positive/c > given: 'large > in: the size field in > the 1st argument of > the eat method in > (class/c > (eat > (->m > (object/c (field (size positive/c))) > void?)) > (field (size positive/c))) > contract from: (definition animal%) > contract on: animal% > blaming: top-level > (assuming the contract is correct) > at: eval:31:0 > ``` There are two important caveats for external class contracts. First, external method contracts are only enforced when the target of dynamic dispatch is the method implementation of the contracted class, which lies within the contract boundary. Overriding that implementation, and thus changing the target of dynamic dispatch, will mean that the contract is no longer enforced for clients, since accessing the method no longer crosses the contract boundary. Unlike external method contracts, external field contracts are always enforced for clients of subclasses, since fields cannot be overridden or shadowed. Second, these contracts do not restrict subclasses of animal% in any way. Fields and methods that are inherited and used by subclasses are not checked by these contracts, and uses of the superclass’s methods via [super](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=createclass.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fclass-internal..rkt%2529._super%2529%2529&version=8.18.0.13) are also unchecked. The following example illustrates both caveats: > ``` (parameter) → (-> object/c (field (size positive/c))) ```
### 13.2 Initialization Arguments (Components) → (-> inherit [ eat (→ m edible/c void?) ])``` > > > The [define-syntax-rule](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=stx-patterns.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fmisc..rkt%2529._define-syntax-rule%2529%2529&version=8.18.0.13) form is itself a macro that expands into [define-syntax](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=define.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._define-syntax%2529%2529&version=8.18.0.13) with a [syntax-rules](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=stx-patterns.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fstxcase-scheme..rkt%2529._syntax-rules%2529%2529&version=8.18.0.13) form that contains only one pattern and template. For example, suppose we would like a rotate macro that generalizes swap to work on either two or three identifiers, so that > ```racket > ( let ( [ red 1 ] [ green 2 ] [ blue 3 ] ) > ( rotate red green ) ; swaps > ( rotate red green blue ) ; rotates left > ( list red green blue ) ) > ``` produces (1 3 2). We can implement rotate using [syntax-rules](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=stx-patterns.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fstxcase-scheme..rkt%2529._syntax-rules%2529%2529&version=8.18.0.13):
### 13.2 Initialization Arguments > ```racket > ( define-syntax rotate > ( syntax-rules ( ) > [ ( rotate a b ) ( swap a b ) ] > [ ( rotate a b c ) ( begin > ( swap a b ) > ( swap b c ) ) ] ) ) > ``` The expression (rotate red green) matches the first pattern in the [syntax-rules](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=stx-patterns.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fstxcase-scheme..rkt%2529._syntax-rules%2529%2529&version=8.18.0.13) form, so it expands to (swap red green). The expression (rotate red green blue) matches the second pattern, so it expands to ([begin](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=begin.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._begin%2529%2529&version=8.18.0.13) (swap red green) (swap green blue)).
#### 16.1.4 Matching Sequences A better rotate macro would allow any number of identifiers, instead of just two or three. To match a use of rotate with any number of identifiers, we need a pattern form that has something like a Kleene star. In a Racket macro pattern, a star is written as [...](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=stx-patterns.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fstxcase-scheme..rkt%2529._......%2529%2529&version=8.18.0.13). To implement rotate with [...](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=stx-patterns.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fstxcase-scheme..rkt%2529._......%2529%2529&version=8.18.0.13), we need a base case to handle a single identifier, and an inductive case to handle more than one identifier: > ```racket > ( define-syntax rotate > ( syntax-rules ( ) > [ ( rotate a ) ( void ) ] > [ ( rotate a b c ... ) ( begin > ( swap a b ) > ( rotate b c ... ) ) ] ) ) > ```
### 13.2 Initialization Arguments When a pattern variable like c is followed by [...](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=stx-patterns.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fstxcase-scheme..rkt%2529._......%2529%2529&version=8.18.0.13) in a pattern, then it must be followed by [...](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=stx-patterns.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fstxcase-scheme..rkt%2529._......%2529%2529&version=8.18.0.13) in a template, too. The pattern variable effectively matches a sequence of zero or more forms, and it is replaced in the template by the same sequence. Both versions of rotate so far are a bit inefficient, since pairwise swapping keeps moving the value from the first variable into every variable in the sequence until it arrives at the last one. A more efficient rotate would move the first value directly to the last variable. We can use [...](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=stx-patterns.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fstxcase-scheme..rkt%2529._......%2529%2529&version=8.18.0.13) patterns to implement the more efficient variant using a helper macro:
### 13.2 Initialization Arguments > ```racket > ( define-syntax rotate > ( syntax-rules ( ) > [ ( rotate a c ... ) > ( shift-to ( c ... a ) ( a c ... ) ) ] ) ) > ( define-syntax shift-to > ( syntax-rules ( ) > [ ( shift-to ( from0 from ... ) ( to0 to ... ) ) > ( let ( [ tmp from0 ] ) > ( set! to from ) ... > ( set! to0 tmp ) ) ] ) ) > ``` In the shift-to macro, [...](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=stx-patterns.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fstxcase-scheme..rkt%2529._......%2529%2529&version=8.18.0.13) in the template follows ([set!](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=set_.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._set%2521%2529%2529&version=8.18.0.13) to from), which causes the ([set!](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=set_.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._set%2521%2529%2529&version=8.18.0.13) to from) expression to be duplicated as many times as necessary to use each identifier matched in the to and from sequences. (The number of to and from matches must be the same, otherwise the macro expansion fails with an error.)
#### 16.1.5 Identifier Macros Given our macro definitions, the swap or rotate identifiers must be used after an open parenthesis, otherwise a syntax error is reported: > ```racket > > ( + swap 3 ) > eval:2:0: swap: bad syntax > in: swap > ``` An identifier macro is a pattern-matching macro that works when used by itself without parentheses. For example, we can define val as an identifier macro that expands to (get-val), so ([+](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=generic-numbers.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._%252B%2529%2529&version=8.18.0.13) val 3) would expand to ([+](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=generic-numbers.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._%252B%2529%2529&version=8.18.0.13) (get-val) 3). > ```racket > > ( define-syntax val ( lambda ( stx ) ( syntax-case stx ( ) [ val ( identifier? ( syntax val ) ) ( syntax ( get-val ) ) ] ) ) ) > > ( define-values ( get-val put-val! ) ( let ( [ private-val 0 ] ) ( values ( lambda ( ) private-val ) ( lambda ( v ) ( set! private-val v ) ) ) ) ) > > val > 0 > > ( + val 3 ) > 3 > ```
### 13.2 Initialization Arguments The val macro uses [syntax-case](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=stx-patterns.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fstxcase-scheme..rkt%2529._syntax-case%2529%2529&version=8.18.0.13), which enables defining more powerful macros and will be explained in the [Mixing Patterns and Expressions: syntax-case](syntax-case.html) section. For now it is sufficient to know that to define a macro, [syntax-case](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=stx-patterns.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fstxcase-scheme..rkt%2529._syntax-case%2529%2529&version=8.18.0.13) is used in a [lambda](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=lambda.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._lambda%2529%2529&version=8.18.0.13), and its templates must be wrapped with an explicit [syntax](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=stx-patterns.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fstxcase-scheme..rkt%2529._syntax%2529%2529&version=8.18.0.13) constructor. Finally, [syntax-case](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=stx-patterns.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fstxcase-scheme..rkt%2529._syntax-case%2529%2529&version=8.18.0.13) clauses may specify additional guard conditions after the pattern.
### 13.2 Initialization Arguments Our val macro uses an [identifier?](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=stxops.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fstx..rkt%2529._identifier%7E3f%2529%2529&version=8.18.0.13) condition to ensure that val must not be used with parentheses. Instead, the macro raises a syntax error: > ```racket > > ( val ) > eval:8:0: val: bad syntax > in: (val) > ```
#### 16.1.6 [set!](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=set_.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._set%2521%2529%2529&version=8.18.0.13) Transformers With the above val macro, we still must call put-val! to change the stored value. It would be more convenient, however, to use [set!](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=set_.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._set%2521%2529%2529&version=8.18.0.13) directly on val. To invoke the macro when val is used with [set!](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=set_.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._set%2521%2529%2529&version=8.18.0.13), we create an [assignment transformer](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=syntax-model.html%23%2528tech._assignment._transformer%2529&version=8.18.0.13) with [make-set!-transformer](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=stxtrans.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._make-set%2521-transformer%2529%2529&version=8.18.0.13). We must also declare [set!](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=set_.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._set%2521%2529%2529&version=8.18.0.13) as a literal in the [syntax-case](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=stx-patterns.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fstxcase-scheme..rkt%2529._syntax-case%2529%2529&version=8.18.0.13) literal list.
### 13.2 Initialization Arguments > ```racket > > ( define-syntax val2 ( make-set!-transformer ( lambda ( stx ) ( syntax-case stx ( set! ) [ val2 ( identifier? ( syntax val2 ) ) ( syntax ( get-val ) ) ] [ ( set! val2 e ) ( syntax ( put-val! e ) ) ] ) ) ) ) > > val2 > 0 > > ( + val2 3 ) > 3 > > ( set! val2 10 ) > > val2 > 10 > ```
#### 16.1.7 Macro-Generating Macros Suppose that we have many identifiers like val and val2 that we’d like to redirect to accessor and mutator functions like get-val and put-val!. We’d like to be able to just write: > (define-get/put-id val get-val put-val!) Naturally, we can implement define-get/put-id as a macro: > ```racket > > ( define-syntax-rule ( define-get/put-id id get put! ) ( define-syntax id ( make-set!-transformer ( lambda ( stx ) ( syntax-case stx ( set! ) [ id ( identifier? ( syntax id ) ) ( syntax ( get ) ) ] [ ( set! id e ) ( syntax ( put! e ) ) ] ) ) ) ) ) > > ( define-get/put-id val3 get-val put-val! ) > > ( set! val3 11 ) > > val3 > 11 > ``` The define-get/put-id macro is a macro-generating macro.
#### 16.1.8 Extended Example: Call-by-Reference Functions We can use pattern-matching macros to add a form to Racket for defining first-order call-by-reference functions. When a call-by-reference function body mutates its formal argument, the mutation applies to variables that are supplied as actual arguments in a call to the function. For example, if define-cbr is like [define](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=define.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._define%2529%2529&version=8.18.0.13) except that it defines a call-by-reference function, then > ```racket > ( define-cbr ( f a b ) > ( swap a b ) ) > ( let ( [ x 1 ] [ y 2 ] ) > ( f x y ) > ( list x y ) ) > ``` produces (2 1). We will implement call-by-reference functions by having function calls supply accessor and mutators for the arguments, instead of supplying argument values directly. In particular, for the function f above, we’ll generate > ```racket > ( define ( do-f get-a get-b put-a! put-b! ) > ( define-get/put-id a get-a put-a! ) > ( define-get/put-id b get-b put-b! ) > ( swap a b ) ) > ``` and redirect a function call (f x y) to > ```racket > ( do-f ( lambda ( ) x ) > ( lambda ( ) y ) > ( lambda ( v ) ( set! x v ) ) > ( lambda ( v ) ( set! y v ) ) ) > ``` Clearly, then define-cbr is a macro-generating macro, which binds f to a macro that expands to a call of do-f. That is, (define-cbr (f a b) (swap a b)) needs to generate the definition
### 13.2 Initialization Arguments > ```racket > ( define-syntax f > ( syntax-rules ( ) > [ ( id actual ... ) > ( do-f ( lambda ( ) actual ) > ... > ( lambda ( v ) > ( set! actual v ) ) > ... ) ] ) ) > ``` At the same time, define-cbr needs to define do-f using the body of f, this second part is slightly more complex, so we defer most of it to a define-for-cbr helper module, which lets us write define-cbr easily enough: > ```racket > ( define-syntax-rule ( define-cbr ( id arg ... ) body ) > ( begin > ( define-syntax id > ( syntax-rules ( ) > [ ( id actual ( ... ... ) ) > ( do-f ( lambda ( ) actual ) > ( ... ... ) > ( lambda ( v ) > ( set! actual v ) ) > ( ... ... ) ) ] ) ) > ( define-for-cbr do-f ( arg ... ) > ( ) ; explained below... > body ) ) ) > ``` Our remaining task is to define define-for-cbr so that it converts > (define-for-cbr do-f (a b) () (swap a b)) to the function definition do-f above. Most of the work is generating a define-get/put-id declaration for each argument, a and b, and putting them before the body. Normally, that’s an easy task for [...](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=stx-patterns.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fstxcase-scheme..rkt%2529._......%2529%2529&version=8.18.0.13) in a pattern and template, but this time there’s a catch: we need to generate the names get-a and put-a! as well as get-b and put-b!, and the pattern language provides no way to synthesize identifiers based on existing identifiers.
### 13.2 Initialization Arguments As it turns out, lexical scope gives us a way around this problem. The trick is to iterate expansions of define-for-cbr once for each argument in the function, and that’s why define-for-cbr starts with an apparently useless () after the argument list. We need to keep track of all the arguments seen so far and the get and put names generated for each, in addition to the arguments left to process. After we’ve processed all the identifiers, then we have all the names we need. Here is the definition of define-for-cbr: > ```racket > ( define-syntax define-for-cbr > ( syntax-rules ( ) > [ ( define-for-cbr do-f ( id0 id ... ) > ( gens ... ) body ) > ( define-for-cbr do-f ( id ... ) > ( gens ... ( id0 get put ) ) body ) ] > [ ( define-for-cbr do-f ( ) > ( ( id get put ) ... ) body ) > ( define ( do-f get ... put ... ) > ( define-get/put-id id get put ) ... > body ) ] ) ) > ``` Step-by-step, expansion proceeds as follows: > ```racket > ( define-for-cbr do-f ( a b ) > ( ) ( swap a b ) ) > => ( define-for-cbr do-f ( b ) > ( [ a get_1 put_1 ] ) ( swap a b ) ) > => ( define-for-cbr do-f ( ) > ( [ a get_1 put_1 ] [ b get_2 put_2 ] ) ( swap a b ) ) > => ( define ( do-f get_1 get_2 put_1 put_2 ) > ( define-get/put-id a get_1 put_1 ) > ( define-get/put-id b get_2 put_2 ) > ( swap a b ) ) > ```
### 13.2 Initialization Arguments The “subscripts” on get_1, get_2, put_1, and put_2 are inserted by the macro expander to preserve lexical scope, since the get generated by each iteration of define-for-cbr should not bind the get generated by a different iteration. In other words, we are essentially tricking the macro expander into generating fresh names for us, but the technique illustrates some of the surprising power of pattern-based macros with automatic lexical scope. The last expression eventually expands to just > ```racket > ( define ( do-f get_1 get_2 put_1 put_2 ) > ( let ( [ tmp ( get_1 ) ] ) > ( put_1 ( get_2 ) ) > ( put_2 tmp ) ) ) > ``` which implements the call-by-name function f. To summarize, then, we can add call-by-reference functions to Racket with just three small pattern-based macros: define-cbr, define-for-cbr, and define-get/put-id. ------------------------------------------------------------------------
# 16.2 General Macro Transformers
### 16.2 General Macro Transformers The [define-syntax](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=define.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._define-syntax%2529%2529&version=8.18.0.13) form creates a transformer binding for an identifier, which is a binding that can be used at compile time while expanding expressions to be evaluated at run time. The compile-time value associated with a transformer binding can be anything; if it is a procedure of one argument, then the binding is used as a macro, and the procedure is the macro transformer.