### 5.5 Structure Comparisons
(x)	→
(-> provide (contract-out
    [ report-cost
    (case →
    (integer? integer? . → . string?)
    (string? . → . string?)) ]))```
------------------------------------------------------------------------


# 7.9 Gotchas


### 7.9 Gotchas


#### 7.9.1 Contracts and [eq?](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Equality.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._eq%7E3f%2529%2529&version=8.18.0.13)
As a general rule, adding a contract to a program should either leave the behavior of the program unchanged, or should signal a contract violation. And this is almost true for Racket contracts, with one exception: [eq?](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Equality.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._eq%7E3f%2529%2529&version=8.18.0.13).
The [eq?](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Equality.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._eq%7E3f%2529%2529&version=8.18.0.13) procedure is designed to be fast and does not provide much in the way of guarantees, except that if it returns true, it means that the two values behave identically in all respects. Internally, this is implemented as pointer equality at a low-level so it exposes information about how Racket is implemented (and how contracts are implemented).


# 7.9 Gotchas
Contracts interact poorly with [eq?](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Equality.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._eq%7E3f%2529%2529&version=8.18.0.13) because function contract checking is implemented internally as wrapper functions. For example, consider this module:
> ```racket
> #lang racket
> ( define ( make-adder x )
> ( if ( = 1 x )
> add1
> ( lambda ( y ) ( + x y ) ) ) )
> ( provide ( contract-out
> [ make-adder ( -> number? ( -> number? number? ) ) ] ) )
> ```
It exports the make-adder function that is the usual curried addition function, except that it returns Racket’s [add1](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=generic-numbers.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._add1%2529%2529&version=8.18.0.13) when its input is 1.
You might expect that
> ```racket
> ( eq? ( make-adder 1 )
> ( make-adder 1 ) )
> ```


# 7.9 Gotchas
would return #t, but it does not. If the contract were changed to [any/c](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=data-structure-contracts.html%23%2528def._%2528%2528lib._racket%252Fcontract%252Fprivate%252Fmisc..rkt%2529._any%252Fc%2529%2529&version=8.18.0.13) (or even ([->](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=function-contracts.html%23%2528form._%2528%2528lib._racket%252Fcontract%252Fbase..rkt%2529._-%7E3e%2529%2529&version=8.18.0.13) [number?](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=number-types.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._number%7E3f%2529%2529&version=8.18.0.13) [any/c](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=data-structure-contracts.html%23%2528def._%2528%2528lib._racket%252Fcontract%252Fprivate%252Fmisc..rkt%2529._any%252Fc%2529%2529&version=8.18.0.13))), then the [eq?](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Equality.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._eq%7E3f%2529%2529&version=8.18.0.13) call would return #t.


# 7.9 Gotchas
Moral: Do not use [eq?](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Equality.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._eq%7E3f%2529%2529&version=8.18.0.13) on values that have contracts.


#### 7.9.2 Contract boundaries and [define/contract](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=attaching-contracts-to-values.html%23%2528form._%2528%2528lib._racket%252Fcontract%252Fregion..rkt%2529._define%252Fcontract%2529%2529&version=8.18.0.13)
The contract boundaries established by [define/contract](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=attaching-contracts-to-values.html%23%2528form._%2528%2528lib._racket%252Fcontract%252Fregion..rkt%2529._define%252Fcontract%2529%2529&version=8.18.0.13), which creates a nested contract boundary, are sometimes unintuitive. This is especially true when multiple functions or other values with contracts interact. For example, consider these two interacting functions:
> ```racket
> > ( define/contract ( f x ) ( -> integer? integer? ) x )
> > ( define/contract ( g ) ( -> string? ) ( f "not an integer" ) )
> > ( g )
> f: contract violation
> expected: integer?
> given: "not an integer"
> in: the 1st argument of
> (-> integer? integer?)
> contract from: (function f)
> blaming: top-level
> (assuming the contract is correct)
> at: eval:2:0
> ```
One might expect that the function g will be blamed for breaking the terms of its contract with f. Blaming g would be right if f and g were directly establishing contracts with each other. They aren’t, however. Instead, the access between f and g is mediated through the top-level of the enclosing module.


# 7.9 Gotchas
More precisely, f and the top-level of the module have the ([->](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=function-contracts.html%23%2528form._%2528%2528lib._racket%252Fcontract%252Fbase..rkt%2529._-%7E3e%2529%2529&version=8.18.0.13) [integer?](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=number-types.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._integer%7E3f%2529%2529&version=8.18.0.13) [integer?](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=number-types.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._integer%7E3f%2529%2529&version=8.18.0.13)) contract mediating their interaction; g and the top-level have ([->](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=function-contracts.html%23%2528form._%2528%2528lib._racket%252Fcontract%252Fbase..rkt%2529._-%7E3e%2529%2529&version=8.18.0.13) [string?](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=strings.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._string%7E3f%2529%2529&version=8.18.0.13)) mediating their interaction, but there is no contract directly between f and g. This means that the reference to f in the body of g is really the top-level of the module’s responsibility, not g’s. In other words, the function f has been given to g with no contract between g and the top-level and thus the top-level is blamed.


# 7.9 Gotchas
If we wanted to add a contract between g and the top-level, we can use [define/contract](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=attaching-contracts-to-values.html%23%2528form._%2528%2528lib._racket%252Fcontract%252Fregion..rkt%2529._define%252Fcontract%2529%2529&version=8.18.0.13)’s #:freevar declaration and see the expected blame:
> ```racket
> > ( define/contract ( f x ) ( -> integer? integer? ) x )
> > ( define/contract ( g ) ( -> string? ) #:freevar f ( -> integer? integer? ) ( f "not an integer" ) )
> > ( g )
> f: contract violation
> expected: integer?
> given: "not an integer"
> in: the 1st argument of
> (-> integer? integer?)
> contract from: top-level
> blaming: (function g)
> (assuming the contract is correct)
> at: eval:6:0
> ```
Moral: if two values with contracts should interact, put them in separate modules with contracts at the module boundary or use #:freevar.


#### 7.9.3 Exists Contracts and Predicates
Much like the [eq?](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Equality.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._eq%7E3f%2529%2529&version=8.18.0.13) example above, #:∃ contracts can change the behavior of a program.
Specifically, the [null?](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=pairs.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._null%7E3f%2529%2529&version=8.18.0.13) predicate (and many other predicates) return #f for #:∃ contracts, and changing one of those contracts to [any/c](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=data-structure-contracts.html%23%2528def._%2528%2528lib._racket%252Fcontract%252Fprivate%252Fmisc..rkt%2529._any%252Fc%2529%2529&version=8.18.0.13) means that [null?](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=pairs.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._null%7E3f%2529%2529&version=8.18.0.13) might now return #t instead, resulting in arbitrarily different behavior depending on how this boolean might flow around in the program.
Moral: Do not use predicates on #:∃ contracts.


#### 7.9.4 Defining Recursive Contracts
When defining a self-referential contract, it is natural to use [define](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=define.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._define%2529%2529&version=8.18.0.13). For example, one might try to write a contract on streams like this:
> ```racket
> > ( define stream/c ( promise/c ( or/c null? ( cons/c number? stream/c ) ) ) )
> stream/c: undefined;
> cannot reference an identifier before its definition
> in module: top-level
> ```
Unfortunately, this does not work because the value of stream/c is needed before it is defined. Put another way, all of the combinators evaluate their arguments eagerly, even though the values that they accept do not.
Instead, use
> ```racket
> ( define stream/c
> ( promise/c
> ( or/c
> null?
> ( cons/c number? ( recursive-contract stream/c ) ) ) ) )
> ```
The use of [recursive-contract](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=contract-utilities.html%23%2528form._%2528%2528lib._racket%252Fcontract%252Fprivate%252Fbase..rkt%2529._recursive-contract%2529%2529&version=8.18.0.13) delays the evaluation of the identifier stream/c until after the contract is first checked, long enough to ensure that stream/c is defined.
See also [Checking Properties of Data Structures](contracts-struct.html#%28part._contracts-lazy-contracts%29).


#### 7.9.5 Mixing [set!](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=set_.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._set%2521%2529%2529&version=8.18.0.13) and [contract-out](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=attaching-contracts-to-values.html%23%2528form._%2528%2528lib._racket%252Fcontract%252Fbase..rkt%2529._contract-out%2529%2529&version=8.18.0.13)
The contract library assumes that variables exported via [contract-out](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=attaching-contracts-to-values.html%23%2528form._%2528%2528lib._racket%252Fcontract%252Fbase..rkt%2529._contract-out%2529%2529&version=8.18.0.13) are not assigned to, but does not enforce it. Accordingly, if you try to [set!](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=set_.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._set%2521%2529%2529&version=8.18.0.13) those variables, you may be surprised. Consider the following example:
> ```racket
> > ( module server racket ( define ( inc-x! ) ( set! x ( + x 1 ) ) ) ( define x 0 ) ( provide ( contract-out [ inc-x! ( -> void? ) ] [ x integer? ] ) ) )
> > ( module client racket ( require ' server ) ( define ( print-latest ) ( printf "x is ~s\n" x ) ) ( print-latest ) ( inc-x! ) ( print-latest ) )
> > ( require ' client )
> x is 0 x is 0
> ```


# 7.9 Gotchas
Both calls to print-latest print 0, even though the value of x has been incremented (and the change is visible inside the module x).
To work around this, export accessor functions, rather than exporting the variable directly, like this:
> ```racket
> #lang racket
> ( define ( get-x ) x )
> ( define ( inc-x! ) ( set! x ( + x 1 ) ) )
> ( define x 0 )
> ( provide ( contract-out [ inc-x! ( -> void? ) ]
> [ get-x ( -> integer? ) ] ) )
> ```
Moral: This is a bug that we will address in a future release.
------------------------------------------------------------------------


# 8 Input and Output


## 8 Input and Output
> > > A Racket port corresponds to the Unix notion of a stream (not to be confused with [racket/stream](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=streams.html&version=8.18.0.13)’s streams).
A Racket port represents a source or sink of data, such as a file, a terminal, a TCP connection, or an in-memory string. Ports provide sequential access in which data can be read or written a piece at a time, without requiring the data to be consumed or produced all at once. More specifically, an input port represents a source from which a program can read data, and an output port represents a sink to which a program can write data.
|                                                                                |
|---------------------------------------------------------------------------------------|
|     [8.1 Varieties of Ports](ports.html)                   |
|     [8.2 Default Ports](default-ports.html)                |
|     [8.3 Reading and Writing Racket Data](read-write.html) |
|     [8.4 Datatypes and Serialization](serialization.html)  |
|     [8.5 Bytes, Characters, and Encodings](encodings.html) |
|     [8.6 I/O Patterns](io-patterns.html)                   |
------------------------------------------------------------------------


# 8.1 Varieties of Ports


### 8.1 Varieties of Ports
Various functions create various kinds of ports. Here are a few examples:
-   Files: The [open-output-file](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=file-ports.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._open-output-file%2529%2529&version=8.18.0.13) function opens a file for writing, and [open-input-file](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=file-ports.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._open-input-file%2529%2529&version=8.18.0.13) opens a file for reading.
    Examples:
    > ```racket
    > > ( define out ( open-output-file "data" ) )
    > > ( display "hello" out )
    > > ( close-output-port out )
    > > ( define in ( open-input-file "data" ) )
    > > ( read-line in )
    > "hello"
    > > ( close-input-port in )
    > ```
    If a file exists already, then [open-output-file](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=file-ports.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._open-output-file%2529%2529&version=8.18.0.13) raises an exception by default. Supply an option like #:exists 'truncate or #:exists 'update to re-write or update the file:
    Examples:
    > ```racket
    > > ( define out ( open-output-file "data" #:exists ' truncate ) )
    > > ( display "howdy" out )
    > > ( close-output-port out )
    > ```


# 8.1 Varieties of Ports
    Instead of having to match the open calls with close calls, most Racket programmers will use the [call-with-input-file](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=file-ports.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._call-with-input-file%2529%2529&version=8.18.0.13) and [call-with-output-file](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=file-ports.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._call-with-output-file%2529%2529&version=8.18.0.13) functions which take a function to call to carry out the desired operation. This function gets as its only argument the port, which is automatically opened and closed for the operation.
    Examples:
    > ```racket
    > > ( call-with-output-file "data" #:exists ' truncate ( lambda ( out ) ( display "hello" out ) ) )
    > > ( call-with-input-file "data" ( lambda ( in ) ( read-line in ) ) )
    > "hello"
    > ```


# 8.1 Varieties of Ports
-   Strings: The [open-output-string](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=stringport.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._open-output-string%2529%2529&version=8.18.0.13) function creates a port that accumulates data into a string, and [get-output-string](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=stringport.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._get-output-string%2529%2529&version=8.18.0.13) extracts the accumulated string. The [open-input-string](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=stringport.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._open-input-string%2529%2529&version=8.18.0.13) function creates a port to read from a string.
    Examples:
    > ```racket
    > > ( define p ( open-output-string ) )
    > > ( display "hello" p )
    > > ( get-output-string p )
    > "hello"
    > > ( read-line ( open-input-string "goodbye\nfarewell" ) )
    > "goodbye"
    > ```


# 8.1 Varieties of Ports
-   TCP Connections: The [tcp-connect](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=tcp.html%23%2528def._%2528%2528lib._racket%252Ftcp..rkt%2529._tcp-connect%2529%2529&version=8.18.0.13) function creates both an input port and an output port for the client side of a TCP communication. The [tcp-listen](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=tcp.html%23%2528def._%2528%2528lib._racket%252Ftcp..rkt%2529._tcp-listen%2529%2529&version=8.18.0.13) function creates a server, which accepts connections via [tcp-accept](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=tcp.html%23%2528def._%2528%2528lib._racket%252Ftcp..rkt%2529._tcp-accept%2529%2529&version=8.18.0.13).
    Examples:
    > ```racket
    > > ( define server ( tcp-listen 12345 ) )
    > > ( define-values ( c-in c-out ) ( tcp-connect "localhost" 12345 ) )
    > > ( define-values ( s-in s-out ) ( tcp-accept server ) )
    > > ( display "hello\n" c-out )
    > > ( close-output-port c-out )
    > > ( read-line s-in )
    > "hello"
    > > ( read-line s-in )
    > #<eof>
    > ```


# 8.1 Varieties of Ports
-   Process Pipes: The [subprocess](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=subprocess.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._subprocess%2529%2529&version=8.18.0.13) function runs a new process at the OS level and returns ports that correspond to the subprocess’s stdin, stdout, and stderr. (The first three arguments can be certain kinds of existing ports to connect directly to the subprocess, instead of creating new ports.)
    Examples:
    > ```racket
    > > ( define-values ( p stdout stdin stderr ) ( subprocess #f #f #f "/usr/bin/wc" "-w" ) )
    > > ( display "a b c\n" stdin )
    > > ( close-output-port stdin )
    > > ( read-line stdout )
    > " 3"
    > > ( close-input-port stdout )
    > > ( close-input-port stderr )
    > ```
-   Internal Pipes: The [make-pipe](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=pipeports.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._make-pipe%2529%2529&version=8.18.0.13) function returns two ports that are ends of a pipe. This kind of pipe is internal to Racket, and not related to OS-level pipes for communicating between different processes.
    Examples:
    > ```racket
    > > ( define-values ( in out ) ( make-pipe ) )
    > > ( display "garbage" out )
    > > ( close-output-port out )
    > > ( read-line in )
    > "garbage"
    > ```
------------------------------------------------------------------------


# 8.2 Default Ports


### 8.2 Default Ports
For most simple I/O functions, the target port is an optional argument, and the default is the current input port or current output port. Furthermore, error messages are written to the current error port, which is an output port. The [current-input-port](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=port-ops.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._current-input-port%2529%2529&version=8.18.0.13), [current-output-port](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=port-ops.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._current-output-port%2529%2529&version=8.18.0.13), and [current-error-port](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=port-ops.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._current-error-port%2529%2529&version=8.18.0.13) functions return the corresponding current ports.
Examples:
> ```racket
> > ( display "Hi" )
> Hi
> > ( display "Hi" ( current-output-port ) ) ; the same
> Hi
> ```
If you start the racket program in a terminal, then the current input, output, and error ports are all connected to the terminal. More generally, they are connected to the OS-level stdin, stdout, and stderr. In this guide, the examples show output written to stdout in purple, and output written to stderr in red italics.
Examples:


# 8.2 Default Ports
> ```racket
> ( define ( swing-hammer ) ( display "Ouch!" ( current-error-port ) ) )
> > ( swing-hammer )
> Ouch!
> ```
The current-port functions are actually [parameters](parameterize.html#%28tech._parameter%29), which means that their values can be set with [parameterize](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=parameters.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fmore-scheme..rkt%2529._parameterize%2529%2529&version=8.18.0.13).
> > > See [Dynamic Binding: parameterize](parameterize.html) for an introduction to parameters.
Example:
> ```racket
> > ( let ( [ s ( open-output-string ) ] ) ( parameterize ( [ current-error-port s ] ) ( swing-hammer ) ( swing-hammer ) ( swing-hammer ) ) ( get-output-string s ) )
> "Ouch!Ouch!Ouch!"
> ```
------------------------------------------------------------------------


# 8.3 Reading and Writing Racket Data


### 8.3 Reading and Writing Racket Data
As noted throughout [Built-In Datatypes](datatypes.html), Racket provides three ways to print an instance of a built-in value:
-   [print](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Writing.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._print%2529%2529&version=8.18.0.13), which prints a value in the same way that is it printed for a [REPL](intro.html#%28tech._repl%29) result; and
-   [write](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Writing.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._write%2529%2529&version=8.18.0.13), which prints a value in such a way that [read](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Reading.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._read%2529%2529&version=8.18.0.13) on the output produces the value back; and


# 8.3 Reading and Writing Racket Data
-   [display](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Writing.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._display%2529%2529&version=8.18.0.13), which tends to reduce a value to just its character or byte content—at least for those datatypes that are primarily about characters or bytes, otherwise it falls back to the same output as [write](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Writing.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._write%2529%2529&version=8.18.0.13).
Here are some examples using each:


# 8.3 Reading and Writing Racket Data
```
> ( print 1/2 )
1/2
> ( print #\x )
#\x
> ( print "hello" )
"hello"
> ( print #"goodbye" )
#"goodbye"
> ( print ' |pea pod| )
'|pea pod|
> ( print ' ( "i" pod ) )
'("i" pod)
> ( print write )
#<procedure:write>   > ( write 1/2 )
1/2
> ( write #\x )
#\x
> ( write "hello" )
"hello"
> ( write #"goodbye" )
#"goodbye"
> ( write ' |pea pod| )
|pea pod|
> ( write ' ( "i" pod ) )
("i" pod)
> ( write write )
#<procedure:write>   > ( display 1/2 )
1/2
> ( display #\x )
x
> ( display "hello" )
hello
> ( display #"goodbye" )
goodbye
> ( display ' |pea pod| )
pea pod
> ( display ' ( "i" pod ) )
(i pod)
> ( display write )
#<procedure:write>```

Overall, [print](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Writing.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._print%2529%2529&version=8.18.0.13) corresponds to the expression layer of Racket syntax, [write](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Writing.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._write%2529%2529&version=8.18.0.13) corresponds to the reader layer, and [display](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Writing.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._display%2529%2529&version=8.18.0.13) roughly corresponds to the character layer.

The [printf](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Writing.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._printf%2529%2529&version=8.18.0.13) function supports simple formatting of data and text. In the format string supplied to [printf](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Writing.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._printf%2529%2529&version=8.18.0.13), \~a [display](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Writing.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._display%2529%2529&version=8.18.0.13)s the next argument, \~s [write](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Writing.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._write%2529%2529&version=8.18.0.13)s the next argument, and \~v [print](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Writing.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._print%2529%2529&version=8.18.0.13)s the next argument.

Examples:

> ```racket
> ( define ( deliver who when what ) ( printf "Items ~a for shopper ~s: ~v" who when what ) )
> > ( deliver ' ( "list" ) ' ( "John" ) ' ( "milk" ) )
> Items (list) for shopper ("John"): '("milk")
> ```

After using [write](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Writing.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._write%2529%2529&version=8.18.0.13), as opposed to [display](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Writing.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._display%2529%2529&version=8.18.0.13) or [print](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Writing.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._print%2529%2529&version=8.18.0.13), many forms of data can be read back in using [read](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Reading.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._read%2529%2529&version=8.18.0.13). The same values [print](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Writing.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._print%2529%2529&version=8.18.0.13)ed can also be parsed by [read](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Reading.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._read%2529%2529&version=8.18.0.13), but the result may have extra quote forms, since a [print](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Writing.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._print%2529%2529&version=8.18.0.13)ed form is meant to be read like an expression.

Examples:

> ```racket
> > ( define-values ( in out ) ( make-pipe ) )
> > ( write "hello" out )
> > ( read in )
> "hello"
> > ( write ' ( "alphabet" soup ) out )
> > ( read in )
> '("alphabet" soup)
> > ( write #hash ( ( a . "apple" ) ( b . "banana" ) ) out )
> > ( read in )
> '#hash((a . "apple") (b . "banana"))
> > ( print ' ( "alphabet" soup ) out )
> > ( read in )
> ''("alphabet" soup)
> > ( display ' ( "alphabet" soup ) out )
> > ( read in )
> '(alphabet soup)
> ```

------------------------------------------------------------------------

# 8.4 Datatypes and Serialization

### 8.4 Datatypes and Serialization

[Prefab](define-struct.html#%28tech._prefab%29) structure types (see [Prefab Structure Types](define-struct.html#%28part._prefab-struct%29)) automatically support serialization: they can be written to an output stream, and a copy can be read back in from an input stream:

> ```racket
> > ( define-values ( in out ) ( make-pipe ) )
> > ( write #s ( sprout bean ) out )
> > ( read in )
> '#s(sprout bean)
> ```

Other structure types created by [struct](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=define-struct.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._struct%2529%2529&version=8.18.0.13), which offer more abstraction than [prefab](define-struct.html#%28tech._prefab%29) structure types, normally [write](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Writing.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._write%2529%2529&version=8.18.0.13) either using #\<....> notation (for opaque structure types) or using #(....) vector notation (for transparent structure types). In neither case can the result be read back in as an instance of the structure type:

> ```racket
> > ( struct posn ( x y ) )
> > ( write ( posn 1 2 ) )
> #<posn>
> > ( define-values ( in out ) ( make-pipe ) )
> > ( write ( posn 1 2 ) out )
> > ( read in )
> pipe::1: read: bad syntax `#<`> ```

> ```racket
> > ( struct posn ( x y ) #:transparent )
> > ( write ( posn 1 2 ) )
> #(struct:posn 1 2)
> > ( define-values ( in out ) ( make-pipe ) )
> > ( write ( posn 1 2 ) out )
> > ( define v ( read in ) )
> > v
> '#(struct:posn 1 2)
> > ( posn? v )
> #f
> > ( vector? v )
> #t
> ```

The [serializable-struct](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=serialization.html%23%2528form._%2528%2528lib._racket%252Fserialize..rkt%2529._serializable-struct%2529%2529&version=8.18.0.13) form defines a structure type that can be [serialize](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=serialization.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fserialize..rkt%2529._serialize%2529%2529&version=8.18.0.13)d to a value that can be printed using [write](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Writing.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._write%2529%2529&version=8.18.0.13) and restored via [read](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Reading.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._read%2529%2529&version=8.18.0.13). The [serialize](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=serialization.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fserialize..rkt%2529._serialize%2529%2529&version=8.18.0.13)d result can be [deserialize](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=serialization.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fserialize..rkt%2529._deserialize%2529%2529&version=8.18.0.13)d to get back an instance of the original structure type. The serialization form and functions are provided by the [racket/serialize](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=serialization.html&version=8.18.0.13) library.

Examples:

> ```racket
> > ( require racket/serialize )
> > ( serializable-struct posn ( x y ) #:transparent )
> > ( deserialize ( serialize ( posn 1 2 ) ) )
> (posn 1 2)
> > ( write ( serialize ( posn 1 2 ) ) )
> ((3) 1 ((#f . deserialize-info:posn-v0)) 0 () () (0 1 2))
> > ( define-values ( in out ) ( make-pipe ) )
> > ( write ( serialize ( posn 1 2 ) ) out )
> > ( deserialize ( read in ) )
> (posn 1 2)
> ```

In addition to the names bound by [struct](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=define-struct.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._struct%2529%2529&version=8.18.0.13), [serializable-struct](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=serialization.html%23%2528form._%2528%2528lib._racket%252Fserialize..rkt%2529._serializable-struct%2529%2529&version=8.18.0.13) binds an identifier with deserialization information, and it automatically [provide](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._provide%2529%2529&version=8.18.0.13)s the deserialization identifier from a module context. This deserialization identifier is accessed reflectively when a value is deserialized.

------------------------------------------------------------------------

# 8.5 Bytes, Characters, and Encodings

### 8.5 Bytes, Characters, and Encodings

Functions like [read-line](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Byte_and_String_Input.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._read-line%2529%2529&version=8.18.0.13), [read](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Reading.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._read%2529%2529&version=8.18.0.13), [display](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Writing.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._display%2529%2529&version=8.18.0.13), and [write](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Writing.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._write%2529%2529&version=8.18.0.13) all work in terms of [characters](characters.html#%28tech._character%29) (which correspond to Unicode scalar values). Conceptually, they are implemented in terms of [read-char](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Byte_and_String_Input.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._read-char%2529%2529&version=8.18.0.13) and [write-char](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Byte_and_String_Output.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._write-char%2529%2529&version=8.18.0.13).

More primitively, ports read and write [bytes](bytestrings.html#%28tech._byte%29), instead of [characters](characters.html#%28tech._character%29). The functions [read-byte](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Byte_and_String_Input.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._read-byte%2529%2529&version=8.18.0.13) and [write-byte](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Byte_and_String_Output.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._write-byte%2529%2529&version=8.18.0.13) read and write raw bytes. Other functions, such as [read-bytes-line](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Byte_and_String_Input.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._read-bytes-line%2529%2529&version=8.18.0.13), build on top of byte operations instead of character operations.

In fact, the [read-char](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Byte_and_String_Input.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._read-char%2529%2529&version=8.18.0.13) and [write-char](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Byte_and_String_Output.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._write-char%2529%2529&version=8.18.0.13) functions are conceptually implemented in terms of [read-byte](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Byte_and_String_Input.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._read-byte%2529%2529&version=8.18.0.13) and [write-byte](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Byte_and_String_Output.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._write-byte%2529%2529&version=8.18.0.13). When a single byte’s value is less than 128, then it corresponds to an ASCII character. Any other byte is treated as part of a UTF-8 sequence, where UTF-8 is a particular standard way of encoding Unicode scalar values in bytes (which has the nice property that ASCII characters are encoded as themselves). Thus, a single [read-char](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Byte_and_String_Input.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._read-char%2529%2529&version=8.18.0.13) may call [read-byte](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Byte_and_String_Input.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._read-byte%2529%2529&version=8.18.0.13) multiple times, and a single [write-char](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Byte_and_String_Output.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._write-char%2529%2529&version=8.18.0.13) may generate multiple output bytes.

The [read-char](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Byte_and_String_Input.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._read-char%2529%2529&version=8.18.0.13) and [write-char](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Byte_and_String_Output.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._write-char%2529%2529&version=8.18.0.13) operations always use a UTF-8 encoding. If you have a text stream that uses a different encoding, or if you want to generate a text stream in a different encoding, use [reencode-input-port](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=port-lib.html%23%2528def._%2528%2528lib._racket%252Fport..rkt%2529._reencode-input-port%2529%2529&version=8.18.0.13) or [reencode-output-port](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=port-lib.html%23%2528def._%2528%2528lib._racket%252Fport..rkt%2529._reencode-output-port%2529%2529&version=8.18.0.13). The [reencode-input-port](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=port-lib.html%23%2528def._%2528%2528lib._racket%252Fport..rkt%2529._reencode-input-port%2529%2529&version=8.18.0.13) function converts an input stream from an encoding that you specify into a UTF-8 stream; that way, [read-char](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Byte_and_String_Input.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._read-char%2529%2529&version=8.18.0.13) sees UTF-8 encodings, even though the original used a different encoding. Beware, however, that [read-byte](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Byte_and_String_Input.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._read-byte%2529%2529&version=8.18.0.13) also sees the re-encoded data, instead of the original byte stream.

------------------------------------------------------------------------

# 8.6 I/O Patterns

### 8.6 I/O Patterns

> > > ([require](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._require%2529%2529&version=8.18.0.13) racket/port) is needed for [#lang](Module_Syntax.html#%28part._hash-lang%29) [racket/base](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=index.html&version=8.18.0.13).

For these examples, say you have two files in the same directory as your program, "oneline.txt" and "manylines.txt".

> "oneline.txt"
>
> > |                                                            |
> > |------------------------------------------------------------|
> > |  I am one line, but there is an empty line after this one. |
> > |                                                            |

> "manylines.txt"
>
> > |                          |
> > |--------------------------|
> > |  I am                    |
> > |  a message               |
> > |  split over a few lines. |
> > |                          |

If you have a file that is quite small, you can get away with reading in the file as a string:

Examples:

> ```racket
> > ( define file-contents ( port->string ( open-input-file "oneline.txt" ) #:close? #t ) )
> > ( string-suffix? file-contents "after this one." )
> #f
> > ( string-suffix? file-contents "after this one.\n" )
> #t
> > ( string-suffix? ( string-trim file-contents ) "after this one." )
> #t
> ```

We use [port->string](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=port-lib.html%23%2528def._%2528%2528lib._racket%252Fport..rkt%2529._port-%7E3estring%2529%2529&version=8.18.0.13) from [racket/port](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=port-lib.html&version=8.18.0.13) to do the reading to a string: the #:close? #t keyword argument ensures that our file is closed after the read.

We use [string-trim](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=strings.html%23%2528def._%2528%2528lib._racket%252Fstring..rkt%2529._string-trim%2529%2529&version=8.18.0.13) from [racket/string](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=strings.html%23%2528mod-path._racket%252Fstring%2529&version=8.18.0.13) to remove any extraneous whitespace at the very beginning and very end of our file. (Lots of formatters out there insist that text files end with a single blank line).

See also [read-line](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Byte_and_String_Input.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._read-line%2529%2529&version=8.18.0.13) if your file has one line of text.

If, instead, you want to process individual lines of a file, then you can use [for](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=for.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._for%2529%2529&version=8.18.0.13) with [in-lines](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=sequences.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._in-lines%2529%2529&version=8.18.0.13):

> ```racket
> > ( define ( upcase-all in ) ( for ( [ l ( in-lines in ) ] ) ( display ( string-upcase l ) ) ( newline ) ) )
> > ( upcase-all ( open-input-string ( string-append "Hello, World!\n" "Can you hear me, now?" ) ) )
> HELLO, WORLD! CAN YOU HEAR ME, NOW?
> ```

You could also combine computations over each line. So if you want to know how many lines contain “m”, you could do:

Example:

> ```racket
> > ( with-input-from-file "manylines.txt" ( lambda ( ) ( for/sum ( [ l ( in-lines ) ] #:when ( string-contains? l "m" ) ) 1 ) ) )
> 2
> ```

Here, [with-input-from-file](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=file-ports.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._with-input-from-file%2529%2529&version=8.18.0.13) from [racket/port](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=port-lib.html&version=8.18.0.13) sets the default input port to be the file "manylines.txt" inside the thunk. It also closes the file after the computation has been completed (and in a few other cases).

However, if you want to determine whether “hello” appears in a file, then you could search separate lines, but it’s even easier to simply apply a regular expression (see [Regular Expressions](regexp.html)) to the stream:

> ```racket
> > ( define ( has-hello? in ) ( regexp-match? #rx"hello" in ) )
> > ( has-hello? ( open-input-string "hello" ) )
> #t
> > ( has-hello? ( open-input-string "goodbye" ) )
> #f
> ```

If you want to copy one port into another, use [copy-port](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=port-lib.html%23%2528def._%2528%2528lib._racket%252Fport..rkt%2529._copy-port%2529%2529&version=8.18.0.13) from [racket/port](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=port-lib.html&version=8.18.0.13), which efficiently transfers large blocks when lots of data is available, but also transfers small blocks immediately if that’s all that is available:

> ```racket
> > ( define o ( open-output-string ) )
> > ( copy-port ( open-input-string "broom" ) o )
> > ( get-output-string o )
> "broom"
> ```

------------------------------------------------------------------------

# 9 Regular Expressions

## 9 Regular Expressions

> > > This chapter is a modified version of \[[Sitaram05](doc-bibliography.html#%28cite._.Sitaram05%29)\].

A regexp value encapsulates a pattern that is described by a string or [byte string](bytestrings.html#%28tech._byte._string%29). The regexp matcher tries to match this pattern against (a portion of) another string or byte string, which we will call the text string, when you call functions like [regexp-match](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=regexp.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._regexp-match%2529%2529&version=8.18.0.13). The text string is treated as raw text, and not as a pattern.

|                                                                                |
|------------------------------------------------------------------------------------------------------------------------------------------------------------|
|     [9.1 Writing Regexp Patterns](regexp-intro.html)                                                                            |
|     [9.2 Matching Regexp Patterns](regexp-match.html)                                                                           |
|     [9.3 Basic Assertions](regexp-assert.html)                                                                                |
|     [9.4 Characters and Character Classes](regexp-chars.html)                                                                   |
|       [9.4.1 Some Frequently Used Character Classes](regexp-chars.html#%28part._.Some_.Frequently_.Used_.Character_.Classes%29) |
|       [9.4.2 POSIX character classes](regexp-chars.html#%28part._.P.O.S.I.X_character_classes%29)                               |
|     [9.5 Quantifiers](regexp-quant.html)                                                                                |
|     [9.6 Clusters](regexp-clusters.html)                                                                                |
|       [9.6.1 Backreferences](regexp-clusters.html#%28part._.Backreferences%29)                                                  |
|       [9.6.2 Non-capturing Clusters](regexp-clusters.html#%28part._.Non-capturing_.Clusters%29)                                 |
|       [9.6.3 Cloisters](regexp-clusters.html#%28part._regexp-cloister%29)                                                       |
|     [9.7 Alternation](regexp-alternation.html)                                                                                |
|     [9.8 Backtracking](Backtracking.html)                                                                                |
|     [9.9 Looking Ahead and Behind](Looking_Ahead_and_Behind.html)                                                               |
|       [9.9.1 Lookahead](Looking_Ahead_and_Behind.html#%28part._.Lookahead%29)                                                   |
|       [9.9.2 Lookbehind](Looking_Ahead_and_Behind.html#%28part._.Lookbehind%29)                                                 |
|     [9.10 An Extended Example](An_Extended_Example.html)                                                                        |

> > > <img src="magnify.png" width="24" height="24" alt="+" />[Regular Expressions](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=regexp.html&version=8.18.0.13) in [The Racket Reference](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=index.html&version=8.18.0.13) provides more on regexps.

------------------------------------------------------------------------

# 9.1 Writing Regexp Patterns

### 9.1 Writing Regexp Patterns

A string or [byte string](bytestrings.html#%28tech._byte._string%29) can be used directly as a [regexp](regexp.html#%28tech._regexp%29) pattern, or it can be prefixed with #rx to form a literal [regexp](regexp.html#%28tech._regexp%29) value. For example, #rx"abc" is a string-based [regexp](regexp.html#%28tech._regexp%29) value, and #rx#"abc" is a [byte string](bytestrings.html#%28tech._byte._string%29)-based [regexp](regexp.html#%28tech._regexp%29) value. Alternately, a string or byte string can be prefixed with #px, as in #px"abc", for a slightly extended syntax of patterns within the string.

Most of the characters in a [regexp](regexp.html#%28tech._regexp%29) pattern are meant to match occurrences of themselves in the [text string](regexp.html#%28tech._text._string%29). Thus, the pattern #rx"abc" matches a string that contains the characters a, b, and c in succession. Other characters act as metacharacters, and some character sequences act as metasequences. That is, they specify something other than their literal selves. For example, in the pattern #rx"a.c", the characters a and c stand for themselves, but the [metacharacter](#%28tech._metacharacter%29) . can match any character. Therefore, the pattern #rx"a.c" matches an a, any character, and c in succession.

> > > When we want a literal \\ inside a Racket string or regexp literal, we must escape it so that it shows up in the string at all. Racket strings use \\ as the escape character, so we end up with two \\s: one Racket-string \\ to escape the regexp \\, which then escapes the .. Another character that would need escaping inside a Racket string is ".

If we needed to match the character . itself, we can escape it by preceding it with a \\. The character sequence \\. is thus a [metasequence](#%28tech._metasequence%29), since it doesn’t match itself but rather just .. So, to match a, ., and c in succession, we use the regexp pattern #rx"a\\\\.c"; the double \\ is an artifact of Racket strings, not the [regexp](regexp.html#%28tech._regexp%29) pattern itself.

The [regexp](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=regexp.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._regexp%2529%2529&version=8.18.0.13) function takes a string or byte string and produces a [regexp](regexp.html#%28tech._regexp%29) value. Use [regexp](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=regexp.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._regexp%2529%2529&version=8.18.0.13) when you construct a pattern to be matched against multiple strings, since a pattern is compiled to a [regexp](regexp.html#%28tech._regexp%29) value before it can be used in a match. The [pregexp](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=regexp.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._pregexp%2529%2529&version=8.18.0.13) function is like [regexp](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=regexp.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._regexp%2529%2529&version=8.18.0.13), but using the extended syntax. Regexp values as literals with #rx or #px are compiled once and for all when they are read.

The [regexp-quote](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=regexp.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._regexp-quote%2529%2529&version=8.18.0.13) function takes an arbitrary string and returns a string for a pattern that matches exactly the original string. In particular, characters in the input string that could serve as regexp metacharacters are escaped with a backslash, so that they safely match only themselves.

> ```racket
> > ( regexp-quote "cons" )
> "cons"
> > ( regexp-quote "list?" )
> "list\\?"
> ```

The [regexp-quote](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=regexp.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._regexp-quote%2529%2529&version=8.18.0.13) function is useful when building a composite [regexp](regexp.html#%28tech._regexp%29) from a mix of [regexp](regexp.html#%28tech._regexp%29) strings and verbatim strings.

------------------------------------------------------------------------

# 9.2 Matching Regexp Patterns

### 9.2 Matching Regexp Patterns

The [regexp-match-positions](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=regexp.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._regexp-match-positions%2529%2529&version=8.18.0.13) function takes a [regexp](regexp.html#%28tech._regexp%29) pattern and a [text string](regexp.html#%28tech._text._string%29), and it returns a match if the regexp matches (some part of) the [text string](regexp.html#%28tech._text._string%29), or #f if the regexp did not match the string. A successful match produces a list of index pairs.

Examples:

> ```racket
> > ( regexp-match-positions #rx"brain" "bird" )
> #f
> > ( regexp-match-positions #rx"needle" "hay needle stack" )
> '((4 . 10))
> ```

In the second example, the integers 4 and 10 identify the substring that was matched. The 4 is the starting (inclusive) index, and 10 the ending (exclusive) index of the matching substring:

> ```racket
> > ( substring "hay needle stack" 4 10 )
> "needle"
> ```

In this first example, [regexp-match-positions](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=regexp.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._regexp-match-positions%2529%2529&version=8.18.0.13)’s return list contains only one index pair, and that pair represents the entire substring matched by the regexp. When we discuss [subpatterns](regexp-clusters.html#%28tech._subpattern%29) later, we will see how a single match operation can yield a list of [submatch](regexp-clusters.html#%28tech._submatch%29)es.

The [regexp-match-positions](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=regexp.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._regexp-match-positions%2529%2529&version=8.18.0.13) function takes optional third and fourth arguments that specify the indices of the [text string](regexp.html#%28tech._text._string%29) within which the matching should take place.

> ```racket
> > ( regexp-match-positions #rx"needle" "his needle stack -- my needle stack -- her needle stack" 20 39 )
> '((23 . 29))
> ```

Note that the returned indices are still reckoned relative to the full [text string](regexp.html#%28tech._text._string%29).

The [regexp-match](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=regexp.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._regexp-match%2529%2529&version=8.18.0.13) function is like [regexp-match-positions](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=regexp.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._regexp-match-positions%2529%2529&version=8.18.0.13), but instead of returning index pairs, it returns the matching substrings:

> ```racket
> > ( regexp-match #rx"brain" "bird" )
> #f
> > ( regexp-match #rx"needle" "hay needle stack" )
> '("needle")
> ```

When [regexp-match](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=regexp.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._regexp-match%2529%2529&version=8.18.0.13) is used with byte-string regexp, the result is a matching byte substring:

> ```racket
> > ( regexp-match #rx#"needle" #"hay needle stack" )
> '(#"needle")
> ```

> > > A byte-string regexp can be applied to a string, and a string regexp can be applied to a byte string. In both cases, the result is a byte string. Internally, all regexp matching is in terms of bytes, and a string regexp is expanded to a regexp that matches UTF-8 encodings of characters. For maximum efficiency, use byte-string matching instead of string, since matching bytes directly avoids UTF-8 encodings.

If you have data that is in a port, there’s no need to first read it into a string. Functions like [regexp-match](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=regexp.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._regexp-match%2529%2529&version=8.18.0.13) can match on the port directly:

> ```racket
> > ( define-values ( i o ) ( make-pipe ) )
> > ( write "hay needle stack" o )
> > ( close-output-port o )
> > ( regexp-match #rx#"needle" i )
> '(#"needle")
> ```

The [regexp-match?](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=regexp.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._regexp-match%7E3f%2529%2529&version=8.18.0.13) function is like [regexp-match-positions](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=regexp.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._regexp-match-positions%2529%2529&version=8.18.0.13), but simply returns a boolean indicating whether the match succeeded:

> ```racket
> > ( regexp-match? #rx"brain" "bird" )
> #f
> > ( regexp-match? #rx"needle" "hay needle stack" )
> #t
> ```

The [regexp-split](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=regexp.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._regexp-split%2529%2529&version=8.18.0.13) function takes two arguments, a [regexp](regexp.html#%28tech._regexp%29) pattern and a text string, and it returns a list of substrings of the text string; the pattern identifies the delimiter separating the substrings.

> ```racket
> > ( regexp-split #rx":" "/bin:/usr/bin:/usr/bin/X11:/usr/local/bin" )
> '("/bin" "/usr/bin" "/usr/bin/X11" "/usr/local/bin")
> > ( regexp-split #rx" " "pea soup" )
> '("pea" "soup")
> ```

If the first argument matches empty strings, then the list of all the single-character substrings is returned.

> ```racket
> > ( regexp-split #rx"" "smithereens" )
> '("" "s" "m" "i" "t" "h" "e" "r" "e" "e" "n" "s" "")
> ```

Thus, to identify one-or-more spaces as the delimiter, take care to use the regexp #rx" +", not #rx" \*".

> ```racket
> > ( regexp-split #rx" +" "split pea soup" )
> '("split" "pea" "soup")
> > ( regexp-split #rx" *" "split pea soup" )
> '("" "s" "p" "l" "i" "t" "" "p" "e" "a" "" "s" "o" "u" "p" "")
> ```

The [regexp-replace](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=regexp.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._regexp-replace%2529%2529&version=8.18.0.13) function replaces the matched portion of the text string by another string. The first argument is the pattern, the second the text string, and the third is either the string to be inserted or a procedure to convert matches to the insert string.

> ```racket
> > ( regexp-replace #rx"te" "liberte" "ty" )
> "liberty"
> > ( regexp-replace #rx"." "racket" string-upcase )
> "Racket"
> ```

If the pattern doesn’t occur in the text string, the returned string is identical to the text string.

The [regexp-replace*](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=regexp.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._regexp-replace%252A%2529%2529&version=8.18.0.13) function replaces all matches in the text string by the insert string:

> ```racket
> > ( regexp-replace* #rx"te" "liberte egalite fraternite" "ty" )
> "liberty egality fratyrnity"
> > ( regexp-replace* #rx"[ds]" "drracket" string-upcase )
> "Drracket"
> ```

------------------------------------------------------------------------

# 9.3 Basic Assertions

### 9.3 Basic Assertions

The assertions ^ and $ identify the beginning and the end of the text string, respectively. They ensure that their adjoining regexps match at one or other end of the text string:

> ```racket
> > ( regexp-match-positions #rx"^contact" "first contact" )
> #f
> ```

The [regexp](regexp.html#%28tech._regexp%29) above fails to match because contact does not occur at the beginning of the text string. In

> ```racket
> > ( regexp-match-positions #rx"laugh$" "laugh laugh laugh laugh" )
> '((18 . 23))
> ```

the regexp matches the last laugh.

The metasequence \\b asserts that a word boundary exists, but this metasequence works only with #px syntax. In

> ```racket
> > ( regexp-match-positions #px"yack\\b" "yackety yack" )
> '((8 . 12))
> ```

the yack in yackety doesn’t end at a word boundary so it isn’t matched. The second yack does and is.

The metasequence \\B (also #px only) has the opposite effect to \\b; it asserts that a word boundary does not exist. In

> ```racket
> > ( regexp-match-positions #px"an\\B" "an analysis" )
> '((3 . 5))
> ```

the an that doesn’t end in a word boundary is matched.

------------------------------------------------------------------------

# 9.4 Characters and Character Classes

### 9.4 Characters and Character Classes

Typically, a character in the regexp matches the same character in the text string. Sometimes it is necessary or convenient to use a regexp [metasequence](regexp-intro.html#%28tech._metasequence%29) to refer to a single character. For example, the metasequence \\. matches the period character.

The [metacharacter](regexp-intro.html#%28tech._metacharacter%29) . matches any character (other than newline in [multi-line mode](regexp-clusters.html#%28tech._multi._line._mode%29); see [Cloisters](regexp-clusters.html#%28part._regexp-cloister%29)):

> ```racket
> > ( regexp-match #rx"p.t" "pet" )
> '("pet")
> ```

The above pattern also matches pat, pit, pot, put, and p8t, but not peat or pfffft.

A character class matches any one character from a set of characters. A typical format for this is the bracketed character class \[...\], which matches any one character from the non-empty sequence of characters enclosed within the brackets. Thus, #rx"p\[aeiou\]t" matches pat, pet, pit, pot, put, and nothing else.

Inside the brackets, a - between two characters specifies the Unicode range between the characters. For example, #rx"ta\[b-dgn-p\]" matches tab, tac, tad, tag, tan, tao, and tap.

An initial ^ after the left bracket inverts the set specified by the rest of the contents; i.e., it specifies the set of characters other than those identified in the brackets. For example, #rx"do\[^g\]" matches all three-character sequences starting with do except dog.

Note that the [metacharacter](regexp-intro.html#%28tech._metacharacter%29) ^ inside brackets means something quite different from what it means outside. Most other [metacharacters](regexp-intro.html#%28tech._metacharacter%29) (., \*, +, ?, etc.) cease to be [metacharacters](regexp-intro.html#%28tech._metacharacter%29) when inside brackets, although you may still escape them for peace of mind. A - is a [metacharacter](regexp-intro.html#%28tech._metacharacter%29) only when it’s inside brackets, and when it is neither the first nor the last character between the brackets.

Bracketed character classes cannot contain other bracketed character classes (although they contain certain other types of character classes; see below). Thus, a \[ inside a bracketed character class doesn’t have to be a metacharacter; it can stand for itself. For example, #rx"\[a\[b\]" matches a, \[, and b.

Furthermore, since empty bracketed character classes are disallowed, a \] immediately occurring after the opening left bracket also doesn’t need to be a metacharacter. For example, #rx"\[\]ab\]" matches \], a, and b.

#### 9.4.1 Some Frequently Used Character Classes

In #px syntax, some standard character classes can be conveniently represented as metasequences instead of as explicit bracketed expressions: \\d matches a digit (the same as \[0-9\]); \\s matches an ASCII whitespace character; and \\w matches a character that could be part of a “word”.

> > > Following regexp custom, we identify “word” characters as \[A-Za-z0-9\_\], although these are too restrictive for what a Racketeer might consider a “word.”

The upper-case versions of these metasequences stand for the inversions of the corresponding character classes: \\D matches a non-digit, \\S a non-whitespace character, and \\W a non-“word” character.

Remember to include a double backslash when putting these metasequences in a Racket string:

> ```racket
> > ( regexp-match #px"\\d\\d" "0 dear, 1 have 2 read catch 22 before 9" )
> '("22")
> ```

These character classes can be used inside a bracketed expression. For example, #px"\[a-z\\\\d\]" matches a lower-case letter or a digit.

#### 9.4.2 POSIX character classes

A POSIX character class is a special [metasequence](regexp-intro.html#%28tech._metasequence%29) of the form \[:...:\] that can be used only inside a bracketed expression in #px syntax. The POSIX classes supported are

-   \[:alnum:\] — ASCII letters and digits

-   \[:alpha:\] — ASCII letters

-   \[:ascii:\] — ASCII characters

-   \[:blank:\] — ASCII widthful whitespace: space and tab

-   \[:cntrl:\] — “control” characters: ASCII 0 to 31

-   \[:digit:\] — ASCII digits, same as \\d

-   \[:graph:\] — ASCII characters that use ink

-   \[:lower:\] — ASCII lower-case letters

-   \[:print:\] — ASCII ink-users plus widthful whitespace

-   \[:space:\] — ASCII whitespace, same as \\s

-   \[:upper:\] — ASCII upper-case letters

-   \[:word:\] — ASCII letters and \_, same as \\w

-   \[:xdigit:\] — ASCII hex digits

For example, the #px"\[\[:alpha:\]\_\]" matches a letter or underscore.

> ```racket
> > ( regexp-match #px"[[:alpha:]_]" "--x--" )
> '("x")
> > ( regexp-match #px"[[:alpha:]_]" "--_--" )
> '("_")
> > ( regexp-match #px"[[:alpha:]_]" "--:--" )
> #f
> ```

The POSIX class notation is valid only inside a bracketed expression. For instance, \[:alpha:\], when not inside a bracketed expression, will not be read as the letter class. Rather, it is (from previous principles) the character class containing the characters :, a, l, p, h.

> ```racket
> > ( regexp-match #px"[:alpha:]" "--a--" )
> '("a")
> > ( regexp-match #px"[:alpha:]" "--x--" )
> #f
> ```

------------------------------------------------------------------------

# 9.5 Quantifiers

### 9.5 Quantifiers

The quantifiers \*, +, and ? match respectively: zero or more, one or more, and zero or one instances of the preceding subpattern.

> ```racket
> > ( regexp-match-positions #rx"c[ad]*r" "cadaddadddr" )
> '((0 . 11))
> > ( regexp-match-positions #rx"c[ad]*r" "cr" )
> '((0 . 2))
> > ( regexp-match-positions #rx"c[ad]+r" "cadaddadddr" )
> '((0 . 11))
> > ( regexp-match-positions #rx"c[ad]+r" "cr" )
> #f
> > ( regexp-match-positions #rx"c[ad]?r" "cadaddadddr" )
> #f
> > ( regexp-match-positions #rx"c[ad]?r" "cr" )
> '((0 . 2))
> > ( regexp-match-positions #rx"c[ad]?r" "car" )
> '((0 . 3))
> ```

In #px syntax, you can use braces to specify much finer-tuned quantification than is possible with \*, +, ?:

-   The quantifier {m} matches exactly m instances of the preceding [subpattern](regexp-clusters.html#%28tech._subpattern%29); m must be a nonnegative integer.

-   The quantifier {m,n} matches at least m and at most n instances. m and n are nonnegative integers with m less or equal to n. You may omit either or both numbers, in which case m defaults to 0 and n to infinity.

It is evident that + and ? are abbreviations for {1,} and {0,1} respectively, and \* abbreviates {,}, which is the same as {0,}.

> ```racket
> > ( regexp-match #px"[aeiou]{3}" "vacuous" )
> '("uou")
> > ( regexp-match #px"[aeiou]{3}" "evolve" )
> #f
> > ( regexp-match #px"[aeiou]{2,3}" "evolve" )
> #f
> > ( regexp-match #px"[aeiou]{2,3}" "zeugma" )
> '("eu")
> ```

The quantifiers described so far are all greedy: they match the maximal number of instances that would still lead to an overall match for the full pattern.

> ```racket
> > ( regexp-match #rx"<.*>" "<tag1> <tag2> <tag3>" )
> '("<tag1> <tag2> <tag3>")
> ```

To make these quantifiers non-greedy, append a ? to them. Non-greedy quantifiers match the minimal number of instances needed to ensure an overall match.

> ```racket
> > ( regexp-match #rx"<.*?>" "<tag1> <tag2> <tag3>" )
> '("<tag1>")
> ```

The non-greedy quantifiers are \*?, +?, ??, {m}?, and {m,n}?, although {m}? is always the same as {m}. Note that the metacharacter ? has two different uses, and both uses are represented in ??.

------------------------------------------------------------------------

# 9.6 Clusters

### 9.6 Clusters

Clustering—enclosure within parens (...)—identifies the enclosed subpattern as a single entity. It causes the matcher to capture the submatch, or the portion of the string matching the subpattern, in addition to the overall match:

> ```racket
> > ( regexp-match #rx"([a-z]+) ([0-9]+), ([0-9]+)" "jan 1, 1970" )
> '("jan 1, 1970" "jan" "1" "1970")
> ```

Clustering also causes a following quantifier to treat the entire enclosed subpattern as an entity:

> ```racket
> > ( regexp-match #rx"(pu )*" "pu pu platter" )
> '("pu pu " "pu ")
> ```

The number of submatches returned is always equal to the number of subpatterns specified in the regexp, even if a particular subpattern happens to match more than one substring or no substring at all.

> ```racket
> > ( regexp-match #rx"([a-z ]+;)*" "lather; rinse; repeat;" )
> '("lather; rinse; repeat;" " repeat;")
> ```

Here, the \*-quantified subpattern matches three times, but it is the last submatch that is returned.

It is also possible for a quantified subpattern to fail to match, even if the overall pattern matches. In such cases, the failing submatch is represented by #f

> ```racket
> > ( define date-re ; match ‘ month year ' or ‘ month day, year ' ; ; subpattern matches day, if present #rx"([a-z]+) +([0-9]+,)? *([0-9]+)" )
> > ( regexp-match date-re "jan 1, 1970" )
> '("jan 1, 1970" "jan" "1," "1970")
> > ( regexp-match date-re "jan 1970" )
> '("jan 1970" "jan" #f "1970")
> ```

#### 9.6.1 Backreferences

[Submatch](#%28tech._submatch%29)es can be used in the insert string argument of the procedures [regexp-replace](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=regexp.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._regexp-replace%2529%2529&version=8.18.0.13) and [regexp-replace*](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=regexp.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._regexp-replace%252A%2529%2529&version=8.18.0.13). The insert string can use \\n as a backreference to refer back to the nth submatch, which is the substring that matched the nth subpattern. A \\0 refers to the entire match, and it can also be specified as \\&.

> ```racket
> > ( regexp-replace #rx"_(.+?)_" "the _nina_, the _pinta_, and the _santa maria_" "*\\1*" )
> "the *nina*, the _pinta_, and the _santa maria_"
> > ( regexp-replace* #rx"_(.+?)_" "the _nina_, the _pinta_, and the _santa maria_" "*\\1*" )
> "the *nina*, the *pinta*, and the *santa maria*"
> > ( regexp-replace #px"(\\S+) (\\S+) (\\S+)" "eat to live" "\\3 \\2 \\1" )
> "live to eat"
> ```

Use \\\\ in the insert string to specify a literal backslash. Also, \\$ stands for an empty string, and is useful for separating a backreference \\n from an immediately following number.

Backreferences can also be used within a #px pattern to refer back to an already matched subpattern in the pattern. \\n stands for an exact repeat of the nth submatch. Note that \\0, which is useful in an insert string, makes no sense within the regexp pattern, because the entire regexp has not matched yet so you cannot refer back to it.}

> ```racket
> > ( regexp-match #px"([a-z]+) and \\1" "billions and billions" )
> '("billions and billions" "billions")
> ```

Note that the [backreference](#%28tech._backreference%29) is not simply a repeat of the previous subpattern. Rather it is a repeat of the particular substring already matched by the subpattern.

In the above example, the [backreference](#%28tech._backreference%29) can only match billions. It will not match millions, even though the subpattern it harks back to—(\[a-z\]+)—would have had no problem doing so:

> ```racket
> > ( regexp-match #px"([a-z]+) and \\1" "billions and millions" )
> #f
> ```

The following example marks all immediately repeating patterns in a number string:

> ```racket
> > ( regexp-replace* #px"(\\d+)\\1" "123340983242432420980980234" "{\\1,\\1}" )
> "12{3,3}40983{24,24}3242{098,098}0234"
> ```

The following example corrects doubled words:

> ```racket
> > ( regexp-replace* #px"\\b(\\S+) \\1\\b" ( string-append "now is the the time for all good men to " "to come to the aid of of the party" ) "\\1" )
> "now is the time for all good men to come to the aid of the party"
> ```

#### 9.6.2 Non-capturing Clusters

It is often required to specify a cluster (typically for quantification) but without triggering the capture of [submatch](#%28tech._submatch%29) information. Such clusters are called non-capturing. To create a non-capturing cluster, use (?: instead of ( as the cluster opener.

In the following example, a non-capturing cluster eliminates the “directory” portion of a given Unix pathname, and a capturing cluster identifies the basename.

> > > But don’t parse paths with regexps. Use functions like [split-path](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Manipulating_Paths.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._split-path%2529%2529&version=8.18.0.13), instead.

> ```racket
> > ( regexp-match #rx"^(?:[a-z]*/)*([a-z]+)$" "/usr/local/bin/racket" )
> '("/usr/local/bin/racket" "racket")
> ```

#### 9.6.3 Cloisters

The location between the ? and the : of a non-capturing cluster is called a cloister. You can put modifiers there that will cause the enclustered [subpattern](#%28tech._subpattern%29) to be treated specially. The modifier i causes the subpattern to match case-insensitively:

> > > The term cloister is a useful, if terminally cute, coinage from the abbots of Perl.

> ```racket
> > ( regexp-match #rx"(?i:hearth)" "HeartH" )
> '("HeartH")
> ```

The modifier m causes the [subpattern](#%28tech._subpattern%29) to match in multi-line mode, where . does not match a newline character, ^ can match just after a newline, and $ can match just before a newline.

> ```racket
> > ( regexp-match #rx"." "\na\n" )
> '("\n")
> > ( regexp-match #rx"(?m:.)" "\na\n" )
> '("a")
> > ( regexp-match #rx"^A plan$" "A man\nA plan\nA canal" )
> #f
> > ( regexp-match #rx"(?m:^A plan$)" "A man\nA plan\nA canal" )
> '("A plan")
> ```

You can put more than one modifier in the cloister:

> ```racket
> > ( regexp-match #rx"(?mi:^A Plan$)" "a man\na plan\na canal" )
> '("a plan")
> ```

A minus sign before a modifier inverts its meaning. Thus, you can use -i in a subcluster to overturn the case-insensitivities caused by an enclosing cluster.

> ```racket
> > ( regexp-match #rx"(?i:the (?-i:TeX)book)" "The TeXbook" )
> '("The TeXbook")
> ```

The above regexp will allow any casing for the and book, but it insists that TeX not be differently cased.

------------------------------------------------------------------------

# 9.7 Alternation

### 9.7 Alternation

You can specify a list of alternate [subpatterns](regexp-clusters.html#%28tech._subpattern%29) by separating them by \|. The \| separates [subpatterns](regexp-clusters.html#%28tech._subpattern%29) in the nearest enclosing cluster (or in the entire pattern string if there are no enclosing parens).

> ```racket
> > ( regexp-match #rx"f(ee|i|o|um)" "a small, final fee" )
> '("fi" "i")
> > ( regexp-replace* #rx"([yi])s(e[sdr]?|ing|ation)" ( string-append "analyse an energising organisation" " pulsing with noisy organisms" ) "\\1z\\2" )
> "analyze an energizing organization pulsing with noisy organisms"
> ```

Note again that if you wish to use clustering merely to specify a list of alternate subpatterns but do not want the submatch, use (?: instead of (.

> ```racket
> > ( regexp-match #rx"f(?:ee|i|o|um)" "fun for all" )
> '("fo")
> ```

An important thing to note about alternation is that the leftmost matching alternate is picked regardless of its length. Thus, if one of the alternates is a prefix of a later alternate, the latter may not have a chance to match.

> ```racket
> > ( regexp-match #rx"call|call-with-current-continuation" "call-with-current-continuation" )
> '("call")
> ```

To allow the longer alternate to have a shot at matching, place it before the shorter one:

> ```racket
> > ( regexp-match #rx"call-with-current-continuation|call" "call-with-current-continuation" )
> '("call-with-current-continuation")
> ```

In any case, an overall match for the entire regexp is always preferred to an overall non-match. In the following, the longer alternate still wins, because its preferred shorter prefix fails to yield an overall match.

> ```racket
> > ( regexp-match #rx"(?:call|call-with-current-continuation) constrained" "call-with-current-continuation constrained" )
> '("call-with-current-continuation constrained")
> ```

------------------------------------------------------------------------

# 9.8 Backtracking

### 9.8 Backtracking

We’ve already seen that greedy quantifiers match the maximal number of times, but the overriding priority is that the overall match succeed. Consider

> ```racket
> > ( regexp-match #rx"a*a" "aaaa" )
> '("aaaa")
> ```

The regexp consists of two subregexps: a\* followed by a. The subregexp a\* cannot be allowed to match all four a’s in the text string aaaa, even though \* is a greedy quantifier. It may match only the first three, leaving the last one for the second subregexp. This ensures that the full regexp matches successfully.

The regexp matcher accomplishes this via a process called backtracking. The matcher tentatively allows the greedy quantifier to match all four a’s, but then when it becomes clear that the overall match is in jeopardy, it backtracks to a less greedy match of three a’s. If even this fails, as in the call

> ```racket
> > ( regexp-match #rx"a*aa" "aaaa" )
> '("aaaa")
> ```

the matcher backtracks even further. Overall failure is conceded only when all possible backtracking has been tried with no success.

Backtracking is not restricted to greedy quantifiers. Nongreedy quantifiers match as few instances as possible, and progressively backtrack to more and more instances in order to attain an overall match. There is backtracking in alternation too, as the more rightward alternates are tried when locally successful leftward ones fail to yield an overall match.

Sometimes it is efficient to disable backtracking. For example, we may wish to commit to a choice, or we know that trying alternatives is fruitless. A nonbacktracking regexp is enclosed in (?>...).

> ```racket
> > ( regexp-match #rx"(?>a+)." "aaaa" )
> #f
> ```

In this call, the subregexp ?>a+ greedily matches all four a’s, and is denied the opportunity to backtrack. So, the overall match is denied. The effect of the regexp is therefore to match one or more a’s followed by something that is definitely non-a.

------------------------------------------------------------------------

# 9.9 Looking Ahead and Behind

### 9.9 Looking Ahead and Behind

You can have assertions in your pattern that look ahead or behind to ensure that a subpattern does or does not occur. These “look around” assertions are specified by putting the subpattern checked for in a cluster whose leading characters are: ?= (for positive lookahead), ?! (negative lookahead), ?\<= (positive lookbehind), ?\<! (negative lookbehind). Note that the subpattern in the assertion does not generate a match in the final result; it merely allows or disallows the rest of the match.

#### 9.9.1 Lookahead

Positive lookahead with ?= peeks ahead to ensure that its subpattern could match.

> ```racket
> > ( regexp-match-positions #rx"grey(?=hound)" "i left my grey socks at the greyhound" )
> '((28 . 32))
> ```

The regexp #rx"grey(?=hound)" matches grey, but only if it is followed by hound. Thus, the first grey in the text string is not matched.

Negative lookahead with ?! peeks ahead to ensure that its subpattern could not possibly match.

> ```racket
> > ( regexp-match-positions #rx"grey(?!hound)" "the gray greyhound ate the grey socks" )
> '((27 . 31))
> ```

The regexp #rx"grey(?!hound)" matches grey, but only if it is not followed by hound. Thus the grey just before socks is matched.

#### 9.9.2 Lookbehind

Positive lookbehind with ?\<= checks that its subpattern could match immediately to the left of the current position in the text string.> ```racket
> > ( regexp-match-positions #rx"(?<=grey)hound" "the hound in the picture is not a greyhound" )> '((38 . 43))
> ```

The regexp #rx"(?\<=grey)hound" matches hound, but only if it is preceded by grey.

Negative lookbehind with ?\<! checks that its subpattern could not possibly match immediately to the left.> ```racket
> > ( regexp-match-positions #rx"(?<!grey)hound" "the greyhound in the picture is not a hound" )> '((38 . 43))
> ```

The regexp #rx"(?\<!grey)hound" matches hound, but only if it is not preceded by grey.

Lookaheads and lookbehinds can be convenient when they are not confusing.

------------------------------------------------------------------------

# 9.10 An Extended Example

### 9.10 An Extended Example

Here’s an extended example from Friedl’s Mastering Regular Expressions, page 189, that covers many of the features described in this chapter. The problem is to fashion a regexp that will match any and only IP addresses or dotted quads: four numbers separated by three dots, with each number between 0 and 255.

First, we define a subregexp n0-255 that matches 0 through 255:

> ```racket
> > ( define n0-255 ( string-append "(?:" "\\d|" ; 0 through 9 "\\d\\d|" ; 00 through 99 "[01]\\d\\d|" ; 000 through 199 "2[0-4]\\d|" ; 200 through 249 "25[0-5]" ; 250 through 255 ")" ) )
> ```

> > > Note that n0-255 lists prefixes as preferred alternates, which is something we cautioned against in [Alternation](regexp-alternation.html). However, since we intend to anchor this subregexp explicitly to force an overall match, the order of the alternates does not matter.

The first two alternates simply get all single- and double-digit numbers. Since 0-padding is allowed, we need to match both 1 and 01. We need to be careful when getting 3-digit numbers, since numbers above 255 must be excluded. So we fashion alternates to get 000 through 199, then 200 through 249, and finally 250 through 255.

An IP-address is a string that consists of four n0-255s with three dots separating them.

> ```racket
> > ( define ip-re1 ( string-append "^" ; nothing before n0-255 ; the first n0-255 , "(?:" ; then the subpattern of "\\." ; a dot followed by n0-255 ; an n0-255 , ")" ; which is "{3}" ; repeated exactly 3 times "$" ) )
> ; with nothing following
> ```

Let’s try it out:

> ```racket
> > ( regexp-match ( pregexp ip-re1 ) "1.2.3.4" )
> '("1.2.3.4")
> > ( regexp-match ( pregexp ip-re1 ) "55.155.255.265" )
> #f
> ```

which is fine, except that we also have

> ```racket
> > ( regexp-match ( pregexp ip-re1 ) "0.00.000.00" )
> '("0.00.000.00")
> ```

All-zero sequences are not valid IP addresses! Lookahead to the rescue. Before starting to match ip-re1, we look ahead to ensure we don’t have all zeros. We could use positive lookahead to ensure there is a digit other than zero.

> ```racket
> > ( define ip-re ( pregexp ( string-append "(?=.*[1-9])" ; ensure there ' s a non-0 digit ip-re1 ) ) )
> ```

Or we could use negative lookahead to ensure that what’s ahead isn’t composed of only zeros and dots.

> ```racket
> > ( define ip-re ( pregexp ( string-append "(?![0.]*$)" ; not just zeros and dots ; (note: . is not metachar inside [ ... ] ) ip-re1 ) ) )
> ```

The regexp ip-re will match all and only valid IP addresses.

> ```racket
> > ( regexp-match ip-re "1.2.3.4" )
> '("1.2.3.4")
> > ( regexp-match ip-re "0.0.0.0" )
> #f
> ```

------------------------------------------------------------------------

# 10 Exceptions and Control

## 10 Exceptions and Control

Racket provides an especially rich set of control operations—not only operations for raising and catching exceptions, but also operations for grabbing and restoring portions of a computation.

|                                                                       |
|-----------------------------------------------------------------------|
|     [10.1 Exceptions](exns.html)           |
|     [10.2 Prompts and Aborts](prompt.html) |
|     [10.3 Continuations](conts.html)       |

------------------------------------------------------------------------

# 10.1 Exceptions

### 10.1 Exceptions

Whenever a run-time error occurs, an exception is raised. Unless the exception is caught, then it is handled by printing a message associated with the exception, and then escaping from the computation.

> ```racket
> > ( / 1 0 )
> /: division by zero
> > ( car 17 )
> car: contract violation
> expected: pair?
> given: 17
> ```

To catch an exception, use the [with-handlers](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=exns.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fmore-scheme..rkt%2529._with-handlers%2529%2529&version=8.18.0.13) form:

> > ```
(with-handlers ([predicate-expr handler-expr] ...)
> > body ...+ )
```


# 8.3 Reading and Writing Racket Data
(v)	→
(-> with-handlers ([ exn:fail? (lambda (v) ((error-display-handler) (exn-message v) v)) ]) (car 17))```
A [for](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=for.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._for%2529%2529&version=8.18.0.13) loop iterates through the sequence produced by the sequence-expr. For each element of the sequence, [for](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=for.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._for%2529%2529&version=8.18.0.13) binds the element to id, and then it evaluates the bodys for side effects.
Examples:
> ```racket
> > ( for ( [ i ' ( 1 2 3 ) ] ) ( display i ) )
> 123
> > ( for ( [ i "abc" ] ) ( printf "~a..." i ) )
> a...b...c...
> > ( for ( [ i 4 ] ) ( display i ) )
> 0123
> ```


# 8.3 Reading and Writing Racket Data
The [for/list](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=for.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._for%252Flist%2529%2529&version=8.18.0.13) variant of [for](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=for.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._for%2529%2529&version=8.18.0.13) is more Racket-like. It accumulates body results into a list, instead of evaluating body only for side effects. In more technical terms, [for/list](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=for.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._for%252Flist%2529%2529&version=8.18.0.13) implements a list comprehension.
Examples:
> ```racket
> > ( for/list ( [ i ' ( 1 2 3 ) ] ) ( * i i ) )
> '(1 4 9)
> > ( for/list ( [ i "abc" ] ) i )
> '(#\a #\b #\c)
> > ( for/list ( [ i 4 ] ) i )
> '(0 1 2 3)
> ```


# 8.3 Reading and Writing Racket Data
The full syntax of [for](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=for.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._for%2529%2529&version=8.18.0.13) accommodates multiple sequences to iterate in parallel, and the [for*](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=for.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._for%252A%2529%2529&version=8.18.0.13) variant nests the iterations instead of running them in parallel. More variants of [for](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=for.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._for%2529%2529&version=8.18.0.13) and [for*](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=for.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._for%252A%2529%2529&version=8.18.0.13) accumulate body results in different ways. In all of these variants, predicates that prune iterations can be included along with bindings.


# 8.3 Reading and Writing Racket Data
Before details on the variations of [for](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=for.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._for%2529%2529&version=8.18.0.13), though, it’s best to see the kinds of sequence generators that make interesting examples.


### 11.1 Sequence Constructors
The [in-range](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=sequences.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._in-range%2529%2529&version=8.18.0.13) function generates a sequence of numbers, given an optional starting number (which defaults to 0), a number before which the sequence ends, and an optional step (which defaults to 1). Using a non-negative integer k directly as a sequence is a shorthand for ([in-range](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=sequences.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._in-range%2529%2529&version=8.18.0.13) k).
Examples:
> ```racket
> > ( for ( [ i 3 ] ) ( display i ) )
> 012
> > ( for ( [ i ( in-range 3 ) ] ) ( display i ) )
> 012
> > ( for ( [ i ( in-range 1 4 ) ] ) ( display i ) )
> 123
> > ( for ( [ i ( in-range 1 4 2 ) ] ) ( display i ) )
> 13
> > ( for ( [ i ( in-range 4 1 -1 ) ] ) ( display i ) )
> 432
> > ( for ( [ i ( in-range 1 4 1/2 ) ] ) ( printf " ~a " i ) )
> 1 3/2 2 5/2 3 7/2
> ```


### 11.1 Sequence Constructors
The [in-naturals](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=sequences.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._in-naturals%2529%2529&version=8.18.0.13) function is similar, except that the starting number must be an exact non-negative integer (which defaults to 0), the step is always 1, and there is no upper limit. A [for](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=for.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._for%2529%2529&version=8.18.0.13) loop using just [in-naturals](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=sequences.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._in-naturals%2529%2529&version=8.18.0.13) will never terminate unless a body expression raises an exception or otherwise escapes.
Example:
> ```racket
> > ( for ( [ i ( in-naturals ) ] ) ( if ( = i 10 ) ( error "too much!" ) ( display i ) ) )
> 0123456789
> too much!
> ```


### 11.1 Sequence Constructors
The [stop-before](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=sequences.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._stop-before%2529%2529&version=8.18.0.13) and [stop-after](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=sequences.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._stop-after%2529%2529&version=8.18.0.13) functions construct a new sequence given a sequence and a predicate. The new sequence is like the given sequence, but truncated either immediately before or immediately after the first element for which the predicate returns true.
Example:
> ```racket
> > ( for ( [ i ( stop-before "abc def" char-whitespace? ) ] ) ( display i ) )
> abc
> ```


### 11.1 Sequence Constructors
Sequence constructors like [in-list](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=sequences.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._in-list%2529%2529&version=8.18.0.13), [in-vector](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=sequences.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._in-vector%2529%2529&version=8.18.0.13) and [in-string](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=sequences.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._in-string%2529%2529&version=8.18.0.13) simply make explicit the use of a list, vector, or string as a sequence. Along with [in-range](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=sequences.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._in-range%2529%2529&version=8.18.0.13), these constructors raise an exception when given the wrong kind of value, and since they otherwise avoid a run-time dispatch to determine the sequence type, they enable more efficient code generation; see [Iteration Performance](#%28part._for-performance%29) for more information.
Examples:


### 11.1 Sequence Constructors
> ```racket
> > ( for ( [ i ( in-string "abc" ) ] ) ( display i ) )
> abc
> > ( for ( [ i ( in-string ' ( 1 2 3 ) ) ] ) ( display i ) )
> in-string: contract violation
> expected: string?
> given: '(1 2 3)
> ```
> > > <img src="magnify.png" width="24" height="24" alt="+" />[Sequences](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=sequences.html&version=8.18.0.13) in [The Racket Reference](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=index.html&version=8.18.0.13) provides more on sequences.