### 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
>
<colgroup><col style="width: 100%" /></colgroup>

([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])))

> ( send ( new size-10-fish% ) get-size )
> 10


### 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.


# 16.2 General Macro Transformers
|                                                                                |
|----------------------------------------------------------------------------------------------------------------|
|     [16.2.1 Syntax Objects](stx-obj.html)                                           |
|     [16.2.2 Macro Transformer Procedures](macro-transformers.html)                  |
|     [16.2.3 Mixing Patterns and Expressions: syntax-case](syntax-case.html)         |
|     [16.2.4 with-syntax and generate-temporaries](with-syntax.html)                 |
|     [16.2.5 Compile and Run-Time Phases](stx-phases.html)                           |
|     [16.2.6 General Phase Levels](phases.html)                                      |
|       [16.2.6.1 Phases and Bindings](phases.html#%28part._.Phases_and_.Bindings%29) |
|       [16.2.6.2 Phases and Modules](phases.html#%28part._.Phases_and_.Modules%29)   |
|     [16.2.7 Tainted Syntax](stx-certs.html)                                         |
------------------------------------------------------------------------


# 16.2.1 Syntax Objects


#### 16.2.1 Syntax Objects
The input and output of a macro transformer (i.e., source and replacement forms) are represented as syntax objects. A syntax object contains symbols, lists, and constant values (such as numbers) that essentially correspond to 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)d form of the expression. For example, a representation of the expression ([+](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) 1 2) contains the symbol '+ and the numbers 1 and 2, all in a list. In addition to this quoted content, a syntax object associates source-location and lexical-binding information with each part of the form. The source-location information is used when reporting syntax errors (for example), and the lexical-binding information allows the macro system to maintain lexical scope. To accommodate this extra information, the representation of the expression ([+](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) 1 2) is not merely '(+ 1 2), but a packaging of '(+ 1 2) into a syntax object.


# 16.2.1 Syntax Objects
To create a literal syntax object, use the [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) form:
> ```racket
> > ( syntax ( + 1 2 ) )
> #<syntax:eval:1:0 (+ 1 2)>
> ```
In the same way that ' abbreviates [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), #' abbreviates [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):
> ```racket
> > #' ( + 1 2 )
> #<syntax:eval:1:0 (+ 1 2)>
> ```


# 16.2.1 Syntax Objects
A syntax object that contains just a symbol is an identifier syntax object. Racket provides some additional operations specific to identifier syntax objects, including the [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) operation to detect identifiers. Most notably, [free-identifier=?](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=stxcmp.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._free-identifier%7E3d%7E3f%2529%2529&version=8.18.0.13) determines whether two identifiers refer to the same binding:
> ```racket
> > ( identifier? #' car )
> #t
> > ( identifier? #' ( + 1 2 ) )
> #f
> > ( free-identifier=? #' car #' cdr )
> #f
> > ( free-identifier=? #' car #' car )
> #t
> > ( require ( only-in racket/base [ car also-car ] ) )
> > ( free-identifier=? #' car #' also-car )
> #t
> ```
To see the lists, symbols, numbers, etc. within a syntax object, use [syntax->datum](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=stxops.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._syntax-%7E3edatum%2529%2529&version=8.18.0.13):
> ```racket
> > ( syntax->datum #' ( + 1 2 ) )
> '(+ 1 2)
> ```


# 16.2.1 Syntax Objects
The [syntax-e](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=stxops.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._syntax-e%2529%2529&version=8.18.0.13) function is similar to [syntax->datum](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=stxops.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._syntax-%7E3edatum%2529%2529&version=8.18.0.13), but it unwraps a single layer of source-location and lexical-context information, leaving sub-forms that have their own information wrapped as syntax objects:
> ```racket
> > ( syntax-e #' ( + 1 2 ) )
> '(#<syntax:eval:1:0 +> #<syntax:eval:1:0 1> #<syntax:eval:1:0 2>)
> ```
The [syntax-e](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=stxops.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._syntax-e%2529%2529&version=8.18.0.13) function always leaves syntax-object wrappers around sub-forms that are represented via symbols, numbers, and other literal values. The only time it unwraps extra sub-forms is when unwrapping a pair, in which case the [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) of the pair may be recursively unwrapped, depending on how the syntax object was constructed.


# 16.2.1 Syntax Objects
The opposite of [syntax->datum](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=stxops.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._syntax-%7E3edatum%2529%2529&version=8.18.0.13) is, of course, [datum->syntax](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=stxops.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._datum-%7E3esyntax%2529%2529&version=8.18.0.13). In addition to a datum like '(+ 1 2), [datum->syntax](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=stxops.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._datum-%7E3esyntax%2529%2529&version=8.18.0.13) needs an existing syntax object to donate its lexical context, and optionally another syntax object to donate its source location:
> ```racket
> > ( datum->syntax #' lex ' ( + 1 2 ) #' srcloc )
> #<syntax:eval:1:0 (+ 1 2)>
> ```
In the above example, the lexical context of #'lex is used for the new syntax object, while the source location of #'[srcloc](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=exns.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._srcloc%2529%2529&version=8.18.0.13) is used.


# 16.2.1 Syntax Objects
When the second (i.e., the “datum”) argument to [datum->syntax](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=stxops.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._datum-%7E3esyntax%2529%2529&version=8.18.0.13) includes syntax objects, those syntax objects are preserved intact in the result. That is, deconstructing the result with [syntax-e](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=stxops.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._syntax-e%2529%2529&version=8.18.0.13) eventually produces the syntax objects that were given to [datum->syntax](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=stxops.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._datum-%7E3esyntax%2529%2529&version=8.18.0.13).
------------------------------------------------------------------------


# 16.2.2 Macro Transformer Procedures


#### 16.2.2 Macro Transformer Procedures
Any procedure of one argument can be a [macro transformer](proc-macros.html#%28tech._macro._transformer%29). As it turns out, 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 is a macro that expands to a procedure form. For example, if you evaluate 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 directly (instead of placing on the right-hand of a [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), the result is a procedure:
> ```racket
> > ( syntax-rules ( ) [ ( nothing ) something ] )
> #<procedure>
> ```


# 16.2.2 Macro Transformer Procedures
Instead of 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), you can write your own macro transformer procedure directly using [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). The argument to the procedure is a [syntax object](stx-obj.html#%28tech._syntax._object%29) that represents the source form, and the result of the procedure must be a [syntax object](stx-obj.html#%28tech._syntax._object%29) that represents the replacement form:
> ```racket
> > ( define-syntax self-as-string ( lambda ( stx ) ( datum->syntax stx ( format "~s" ( syntax->datum stx ) ) ) ) )
> > ( self-as-string ( + 1 2 ) )
> "(self-as-string (+ 1 2))"
> ```


# 16.2.2 Macro Transformer Procedures
The source form passed to a macro transformer represents an expression in which its identifier is used in an application position (i.e., after a parenthesis that starts an expression), or it represents the identifier by itself if it is used as an expression position and not in an application position.The procedure produced by [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) raises a syntax error if its argument corresponds to a use of the identifier by itself, which is why [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) does not implement an [identifier macro](pattern-macros.html#%28tech._identifier._macro%29).
> ```racket
> > ( self-as-string ( + 1 2 ) )
> "(self-as-string (+ 1 2))"
> > self-as-string
> "self-as-string"
> ```


# 16.2.2 Macro Transformer Procedures
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 supports the same shortcut syntax for functions as [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), so that the following self-as-string definition is equivalent to the one that uses [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) explicitly:
> ```racket
> > ( define-syntax ( self-as-string stx ) ( datum->syntax stx ( format "~s" ( syntax->datum stx ) ) ) )
> > ( self-as-string ( + 1 2 ) )
> "(self-as-string (+ 1 2))"
> ```
------------------------------------------------------------------------


# 16.2.3 Mixing Patterns and Expressions: syntax-case


#### 16.2.3 Mixing Patterns and Expressions: [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)
The procedure generated by [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) internally uses [syntax-e](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=stxops.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._syntax-e%2529%2529&version=8.18.0.13) to deconstruct the given syntax object, and it uses [datum->syntax](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=stxops.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._datum-%7E3esyntax%2529%2529&version=8.18.0.13) to construct the result. 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 doesn’t provide a way to escape from pattern-matching and template-construction mode into an arbitrary Racket expression.


# 16.2.3 Mixing Patterns and Expressions: syntax-case
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) form lets you mix pattern matching, template construction, and arbitrary expressions:
> > ```
(syntax-case stx-expr (literal-id ...)
> > [ pattern expr ]
> > ... )
```
(shifted)	→
(-> syntax-case #' (+ 1 2) () [ (op n1 n2) #' (- n1 n2) ])```
(Simple)	→
(-> Components)
```
(Parsing)	→
(-> - 4 (+ 1 1))```
objects:
defined:
evaluate: ( begin ( define x ( vector 10 20 ) )
( define y x )
( vector-set! x 0 11 )
( vector-ref y 0 ) )
→  objects: (define <o1> (vector 10 20))
defined:
evaluate: ( begin ( define x <o1> )
( define y x )
( vector-set! x 0 11 )
( vector-ref y 0 ) )
→  objects: (define <o1> (vector 10 20))
defined: (define x <o1>)
evaluate: ( begin ( void )
( define y x )
( vector-set! x 0 11 )
( vector-ref y 0 ) )
→  objects: (define <o1> (vector 10 20))
defined: (define x <o1>)
evaluate: ( begin ( define y x )
( vector-set! x 0 11 )
( vector-ref y 0 ) )
→  objects: (define <o1> (vector 10 20))
defined: (define x <o1>)
evaluate: ( begin ( define y <o1> )
( vector-set! x 0 11 )
( vector-ref y 0 ) )
→  objects: (define <o1> (vector 10 20))
defined: ( define x <o1> )
( define y <o1> )
evaluate: ( begin ( void )
( vector-set! x 0 11 )
( vector-ref y 0 ) )
→  objects: (define <o1> (vector 10 20))
defined: ( define x <o1> )
( define y <o1> )
evaluate: ( begin ( vector-set! x 0 11 )
( vector-ref y 0 ) )
→  objects: (define <o1> (vector 10 20))
defined: ( define x <o1> )
( define y <o1> )
evaluate: ( begin ( vector-set! <o1> 0 11 )
( vector-ref y 0 ) )
→  objects: (define <o1> (vector 11 20))
defined: ( define x <o1> )
( define y <o1> )
evaluate: ( begin ( void )
( vector-ref y 0 ) )
→  objects: (define <o1> (vector 11 20))
defined: ( define x <o1> )
( define y <o1> )
evaluate: (vector-ref y 0)
→  objects: (define <o1> (vector 11 20))
defined: ( define x <o1> )
( define y <o1> )
evaluate: (vector-ref <o1> 0)
→  objects: (define <o1> (vector 11 20))
defined: ( define x <o1> )
( define y <o1> )
evaluate: 11


# 16.2.3 Mixing Patterns and Expressions: syntax-case
```

The distinction between a [top-level variable](#%28tech._top._level._variable%29) and an object reference is crucial. A [top-level variable](#%28tech._top._level._variable%29) is not a [value](#%28tech._value%29), so it must be evaluated. Each time a [variable](#%28tech._variable%29) expression is evaluated, the value of the variable is extracted from the current set of definitions. An object reference, in contrast, is a value and therefore needs no further evaluation. The evaluation steps above use angle-bracketed \<o1> for an object reference to distinguish it from a [variable](#%28tech._variable%29) name.

An object reference can never appear directly in a text-based source program. A program representation created with [datum->syntax](stxops.html#%28def._%28%28quote._~23~25kernel%29._datum-~3esyntax%29%29), however, can embed direct references to existing [objects](#%28tech._object%29).

#### 1.1.6 Garbage Collection

> > > <img src="magnify.png" width="24" height="24" alt="+" />See [Memory Management](memory.html) for functions related to garbage collection.

In the program state

```
objects: ( define <o1> ( vector 10 20 ) )
( define <o2> ( vector 0 ) )
defined: (define x <o1>)
evaluate: (+ 1 x)


# 16.2.3 Mixing Patterns and Expressions: syntax-case
```
(x)	→
(-> define \<p1> (lambda (x) (+ x 10)))```
objects: (define <p1> (lambda (x) (+ x 10)))
defined: (define f <p1>)
evaluate: (<p1> 7)
→  objects: (define <p1> (lambda (x) (+ x 10)))
defined: ( define f <p1> )
( define xloc 7 )
evaluate: (+ xloc 10)
→  objects: (define <p1> (lambda (x) (+ x 10)))
defined: ( define f <p1> )
( define xloc 7 )
evaluate: (+ 7 10)
→  objects: (define <p1> (lambda (x) (+ x 10)))
defined: ( define f <p1> )
( define xloc 7 )
evaluate: 17
```
A [location](#%28tech._location%29) is the same as a [top-level variable](#%28tech._top._level._variable%29), but when a [location](#%28tech._location%29) is generated, it (conceptually) uses a name that has not been used before and that cannot be generated again or accessed directly.
Generating a [location](#%28tech._location%29) in this way means that [set!](set_.html#%28form._%28%28quote._~23~25kernel%29._set%21%29%29) evaluates for [local variables](#%28tech._local._variable%29), including argument variables, in the same way as for [top-level variables](#%28tech._top._level._variable%29), because the [local variable](#%28tech._local._variable%29) is always replaced with a [location](#%28tech._location%29) by the time the [set!](set_.html#%28form._%28%28quote._~23~25kernel%29._set%21%29%29) form is evaluated:


# 16.2.3 Mixing Patterns and Expressions: syntax-case
```
objects: (define <p1> (lambda (x) (begin (set! x 3) x)))
defined: (define f <p1>)
evaluate: (f 7)
→  objects: (define <p1> (lambda (x) (begin (set! x 3) x)))
defined: (define f <p1>)
evaluate: (<p1> 7)
→  objects: (define <p1> (lambda (x) (begin (set! x 3) x)))
defined: ( define f <p1> )
( define xloc 7 )
evaluate: (begin (set! xloc 3) xloc)
→  objects: (define <p1> (lambda (x) (begin (set! x 3) x)))
defined: ( define f <p1> )
( define xloc 3 )
evaluate: (begin (void) xloc)
→  objects: (define <p1> (lambda (x) (begin (set! x 3) x)))
defined: ( define f <p1> )
( define xloc 3 )
evaluate: xloc
→  objects: (define <p1> (lambda (x) (begin (set! x 3) x)))
defined: ( define f <p1> )
( define xloc 3 )
evaluate: 3
```
(x)	→
(-> define x ' orig)```
(parameter)	→
(-> #%plain-app variable-reference-from-unsafe?
    (#%variable-reference))
```
(decimal)	→
(-> see Weak Boxes)```
Examples:
 (#1=100 #1# #1#)  reads equal to  (list 100 100 100)
 #0=(1 . #0#)  reads equal to  ( let* ( [ ph ( make-placeholder #f ) ]
[ v ( cons 1 ph ) ] )
(placeholder-set! ph v)
( make-reader-graph v ) )
```
(unquoted)	→
(-> ASCII 32)```
indicates that the result of each parameter-expr must be a value v for which ([parameter?](parameters.html#%28def._%28%28quote._~23~25kernel%29._parameter~3f%29%29) v) returns true.