# 4.15 Hash Tables
> ```racket
> > ( define original-key "hello" )
> > ( define key-copy ( string-copy original-key ) )
> > ( define table0 ( hash ) )
> > ( define table1 ( hash-set table0 original-key ' one ) )
> > ( define table2 ( hash-set table1 key-copy ' two ) )
> > ( eq? ( hash-ref-key table2 "hello" ) original-key )
> #f
> > ( eq? ( hash-ref-key table2 "hello" ) key-copy )
> #t
> ```
If ht is an impersonator, then the returned key will be determined as described in the documentation to impersonate-hash.
See also the caveats concerning concurrent modification and the caveat concerning mutable keys above.
Added in version 7.4.0.3 of package base.
> ```
(hash-ref! ht key to-set)   →   any
  ht : hash?
  key : any/c
  to-set : failure-result/c```
Returns the value for key in ht. If no value is found for key, then to-set determines the result as in [hash-ref](#%28def._%28%28quote._~23~25kernel%29._hash-ref%29%29) (i.e., it is either a thunk that computes a value or a plain value), and this result is stored in ht for the key. (Note that if to-set is a thunk, it is not invoked in tail position.)
See also the [caveats concerning concurrent modification](#%28elem._%28caveat._concurrency%29%29) and the [caveat concerning mutable keys](#%28elem._%28caveat._mutable-keys%29%29) above.
> ```
(hash-has-key? ht key)  →  boolean?
  ht : hash?
  key : any/c


# 4.15 Hash Tables
```
(parameter)	→
(-> and/c hash? (not/c immutable?))```

Updates the value mapped by key in ht by applying updater to the value. The value returned by updater becomes the new mapping for key, overwriting the original value in ht.

Examples:

> ```racket
> ( define h ( make-hash ) ) ( hash-set! h ' a 5 )
> > ( hash-update! h ' a add1 )
> > h
> '#hash((a . 6))
> ```

The optional failure-result argument is used when no mapping exists for key already, in the same manner as in [hash-ref](#%28def._%28%28quote._~23~25kernel%29._hash-ref%29%29).

Examples:

> ```racket
> ( define h ( make-hash ) )
> > ( hash-update! h ' b add1 )
> hash-update!: no value found for key: 'b
> > ( hash-update! h ' b add1 0 )
> > h
> '#hash((b . 1))
> ```

See also the [caveats concerning concurrent modification](#%28elem._%28caveat._concurrency%29%29) and the [caveat concerning mutable keys](#%28elem._%28caveat._mutable-keys%29%29) above.

> ```
(hash-update ht key updater [failure-result)
  →  (and/c hash? immutable?)
  ht : (and/c hash? immutable?)
  key : any/c
  updater : (any/c .  →  . any/c)
   failure-result   :   failure-result/c
      =   ( lambda ( )
> ( raise ( make-exn:fail:contract .... ) ) )
```
(parameter)	→
(-> and/c hash? (not/c immutable?))```
Removes any existing mapping for key in ht.
See also the [caveats concerning concurrent modification](#%28elem._%28caveat._concurrency%29%29) and the [caveat concerning mutable keys](#%28elem._%28caveat._mutable-keys%29%29) above.
> ```


# 4.15 Hash Tables
(hash-remove ht key)  →  (and/c hash? immutable?)
  ht : (and/c hash? immutable?)
  key : any/c
```
(parameter)	→
(-> and/c hash? (not/c immutable?))```

Removes all mappings from ht.

If ht is not an [impersonator](chaperones.html#%28tech._impersonator%29), then all mappings are removed in constant time. If ht is an [impersonator](chaperones.html#%28tech._impersonator%29), then each key is removed one-by-one using [hash-remove!](#%28def._%28%28quote._~23~25kernel%29._hash-remove%21%29%29).

See also the [caveats concerning concurrent modification](#%28elem._%28caveat._concurrency%29%29) and the [caveat concerning mutable keys](#%28elem._%28caveat._mutable-keys%29%29) above.

> ```
(hash-clear ht)  →  (and/c hash? immutable?)
  ht : (and/c hash? immutable?)
```
Functionally removes all mappings from ht.
If ht is not a chaperone, then clearing is equivalent to creating a new hash table, and the operation is performed in constant time. If ht is a chaperone, then each key is removed one-by-one using hash-remove.
> ```
(hash-copy-clear ht [#:kind kind) → hash?
  ht : hash?
  kind : (or/c #f 'immutable 'mutable 'weak 'ephemeron) = #f```
Produces an empty [hash table](#%28tech._hash._table%29) with the same key-comparison procedure as ht, with either the given kind or the same kind as the given ht.


# 4.15 Hash Tables
If kind is not supplied or #f, produces a hash table of the same kind and mutability as the given ht. If kind is 'immutable, 'mutable, 'weak, or 'ephemeron, produces a table that’s immutable, mutable with strongly-held keys, mutable with weakly-held keys, or mutable with ephemeron-held keys respectively.
Changed in version 8.5.0.2 of package base: Added the kind argument.
> ```
(hash-map ht proc [try-order?) → (listof any/c)
  ht : hash?
  proc : (any/c any/c .  →  . any/c)
  try-order? : any/c = #f
```
Applies the procedure proc to each element in ht in an unspecified order, accumulating the results into a list. The procedure proc is called each time with a key and its value, and the procedure’s individual results appear in order in the result list.

If a hash table is extended with new keys (either through proc or by another thread) while a hash-map or hash-for-each traversal is in process, arbitrary key–value pairs can be dropped or duplicated in the traversal. Key mappings can be deleted or remapped (by any thread) with no adverse affects; the change does not affect a traversal if the key has been seen already, otherwise the traversal skips a deleted key or uses the remapped key’s new value.

See also the caveats concerning concurrent modification above.

If try-order? is true, then the order of keys and values passed to proc is normalized under certain circumstances—including when every key is one of the following and with the following order (earlier bullets before later):

-  booleans sorted #f before #t;

-  characters sorted by char<?;

-  real numbers sorted by <;

-  symbols sorted with uninterned symbols before unreadable symbols before interned symbols, then sorted by symbol<?;

-  keywords sorted by keyword<?;

-  strings sorted by string<?;

-  byte strings sorted by bytes<?;

-  null;

-  #<void>; and

-  eof.

Changed in version 6.3 of package base: Added the try-order? argument.
Changed in version 7.1.0.7: Added guarantees for try-order?.

Examples:

> ```racket
> > ( hash-map ( make-hash ' ( [ 0 . 1 ] [ 1 . 2 ] [ 2 . 3 ] ) ) ( λ ( k v ) k ) )
> '(0 1 2)
> > ( hash-map ( make-hash ' ( [ 0 . 1 ] [ 1 . 2 ] [ 2 . 3 ] ) ) ( λ ( k v ) v ) )
> '(1 2 3)
> ```

> ```
(hash-map/copy ht proc [#:kind kind) → hash?
  ht : hash?
  proc : (any/c any/c .  →  . (values any/c any/c))
  kind : (or/c #f 'immutable 'mutable 'weak 'ephemeron) = #f```

Applies the procedure proc to each element in ht in an unspecified order, accumulating the results into a new hash with the same key-comparison procedure as ht, with either the given kind or the same kind as the given ht.

If kind is not supplied or #f, produces a hash table of the same kind and mutability as the given ht. If kind is 'immutable, 'mutable, 'weak, or 'ephemeron, produces a table that’s immutable, mutable with strongly-held keys, mutable with weakly-held keys, or mutable with ephemeron-held keys respectively.

Examples:

> ```racket
> > ( hash-map/copy #hash ( ( a . "apple" ) ( b . "banana" ) ) ( lambda ( k v ) ( values k ( string-upcase v ) ) ) )
> '#hash((a . "APPLE") (b . "BANANA"))
> > ( define frozen-capital ( hash-map/copy ( make-hash ' ( ( a . "apple" ) ( b . "banana" ) ) ) ( lambda ( k v ) ( values k ( string-upcase v ) ) ) #:kind ' immutable ) )
> > frozen-capital
> '#hash((a . "APPLE") (b . "BANANA"))
> > ( immutable? frozen-capital )
> #t
> ```

Added in version 8.5.0.2 of package base.

> ```
(hash-keys ht [try-order?) → (listof any/c)
  ht : hash?
  try-order? : any/c = #f
```


# 4.15 Hash Tables
Returns a list of the keys of ht in an unspecified order.
If try-order? is true, then the order of keys is normalized under certain circumstances. See hash-map for further explanations on try-order? and on information about modifying ht during hash-keys.
See also the caveats concerning concurrent modification above.
Changed in version 8.3.0.11 of package base: Added the try-order? argument.
> ```
(hash-values ht [try-order?) → (listof any/c)
  ht : hash?
  try-order? : any/c = #f```
Returns a list of the values of ht in an unspecified order.
If try-order? is true, then the order of values is normalized under certain circumstances, based on the ordering of the associated keys. See [hash-map](#%28def._%28%28quote._~23~25kernel%29._hash-map%29%29) for further explanations on try-order? and on information about modifying ht during [hash-values](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._hash-values%29%29).
See also the [caveats concerning concurrent modification](#%28elem._%28caveat._concurrency%29%29) above.
Changed in version 8.3.0.11 of package base: Added the try-order? argument.
> ```
(hash → list ht [try-order?) → (listof (cons/c any/c any/c))
  ht : hash?
  try-order? : any/c = #f


# 4.15 Hash Tables
```
Returns a list of the key–value pairs of ht in an unspecified order.

If try-order? is true, then the order of keys and values is normalized under certain circumstances. See hash-map for further explanations on try-order? and on information about modifying ht during hash  →  list.

See also the caveats concerning concurrent modification above.

Changed in version 8.3.0.11 of package base: Added the try-order? argument.

> ```
(hash-keys-subset? ht1 ht2)   →   boolean?
  ht1 : hash?
  ht2 : hash?```

Returns #t if the keys of ht1 are a subset of or the same as the keys of ht2. The hash tables must both use the same key-comparison function ([equal?](Equality.html#%28def._%28%28quote._~23~25kernel%29._equal~3f%29%29), [equal-always?](Equality.html#%28def._%28%28quote._~23~25kernel%29._equal-always~3f%29%29), [eqv?](Equality.html#%28def._%28%28quote._~23~25kernel%29._eqv~3f%29%29), or [eq?](Equality.html#%28def._%28%28quote._~23~25kernel%29._eq~3f%29%29)), otherwise the [exn:fail:contract](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3acontract%29%29) exception is raised.

Using [hash-keys-subset?](#%28def._%28%28quote._~23~25kernel%29._hash-keys-subset~3f%29%29) on immutable hash tables can be much faster than iterating through the keys of ht1 to make sure that each is in ht2.

Added in version 6.5.0.8 of package base.

> ```
(parameter)	→
(-> any/c any/c . → . any)
```
Applies proc to each element in ht (for the side-effects of proc) in an unspecified order. The procedure proc is called each time with a key and its value.


# 4.15 Hash Tables
See hash-map for information about try-order? and about modifying ht within proc.
See also the caveats concerning concurrent modification above.
Changed in version 6.3 of package base: Added the try-order? argument.
Changed in version 7.1.0.7: Added guarantees for try-order?.
> ```
(hash-count ht)   →   exact-nonnegative-integer?
  ht : hash?```
Returns the number of keys mapped by ht.
For the [CS](implementations.html#%28tech._c%29) implementation of Racket, the result is always computed in constant time and atomically. For the [BC](implementations.html#%28tech._bc%29) implementation of Racket, the result is computed in constant time and atomically only if ht does not retain keys weakly or like an [ephemeron](ephemerons.html#%28tech._ephemeron%29), otherwise, a traversal is required to count the keys.
> ```
(hash-empty? ht)  →  boolean?
  ht : hash?


# 4.15 Hash Tables
```
Equivalent to (zero? (hash-count ht)).

> ```
(hash-iterate-first ht)   →   (or/c #f exact-nonnegative-integer?)
  ht : hash?```

Returns #f if ht contains no elements, otherwise it returns an integer that is an index to the first element in the hash table; “first” refers to an unspecified ordering of the table elements, and the index values are not necessarily consecutive integers.

For a mutable ht, this index is guaranteed to refer to the first item only as long as no items are added to or removed from ht. More generally, an index is guaranteed to be a valid hash index for a given hash table only as long it comes from [hash-iterate-first](#%28def._%28%28quote._~23~25kernel%29._hash-iterate-first%29%29) or [hash-iterate-next](#%28def._%28%28quote._~23~25kernel%29._hash-iterate-next%29%29), and only as long as the hash table is not modified. In the case of a hash table with weakly held keys or keys held like [ephemerons](ephemerons.html#%28tech._ephemeron%29), the hash table can be implicitly modified by the garbage collector (see [Garbage Collection](eval-model.html#%28part._gc-model%29)) when it discovers that the key is not reachable.

> ```
(hash-iterate-next ht pos)
  →  (or/c #f exact-nonnegative-integer?)
  ht : hash?
  pos : exact-nonnegative-integer?
```
Returns either an integer that is an index to the element in ht after the element indexed by pos (which is not necessarily one more than pos) or #f if pos refers to the last element in ht.


# 4.15 Hash Tables
If pos is not a valid hash index of ht, then the result may be #f or it may be the next later index that remains valid. The latter result is guaranteed if a hash table has been modified only by the removal of keys.
Changed in version 7.0.0.10 of package base: Handle an invalid index by returning #f instead of raising exn:fail:contract.
> ```
(hash-iterate-key ht pos)   →   any/c
  ht : hash?
  pos : exact-nonnegative-integer?
(hash-iterate-key ht pos bad-index-v)   →   any/c
  ht : hash?
  pos : exact-nonnegative-integer?
  bad-index-v : any/c```
Returns the key for the element in ht at index pos.
If pos is not a [valid hash index](#%28tech._valid._hash._index%29) for ht, the result is bad-index-v if provided, otherwise the [exn:fail:contract](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3acontract%29%29) exception is raised.
Changed in version 7.0.0.10 of package base: Added the optional bad-index-v argument.
> ```
(hash-iterate-value ht pos)  →  any/c
  ht : hash?
  pos : exact-nonnegative-integer?
(hash-iterate-value ht pos bad-index-v)  →  any/c
  ht : hash?
  pos : exact-nonnegative-integer?
  bad-index-v : any/c


# 4.15 Hash Tables
```
Returns the value for the element in ht at index pos.

If pos is not a valid hash index for ht, the result is bad-index-v if provided, otherwise the exn:fail:contract exception is raised.

Changed in version 7.0.0.10 of package base: Added the optional bad-index-v argument.

> ```
(hash-iterate-pair ht pos)   →   (cons/c any/c any/c)
  ht : hash?
  pos : exact-nonnegative-integer?

(hash-iterate-pair ht pos bad-index-v)   →   (cons/c any/c any/c)
  ht : hash?
  pos : exact-nonnegative-integer?
  bad-index-v : any/c```

Returns a pair containing the key and value for the element in ht at index pos.

If pos is not a [valid hash index](#%28tech._valid._hash._index%29) for ht, the result is ([cons](pairs.html#%28def._%28%28quote._~23~25kernel%29._cons%29%29) bad-index-v bad-index-v) if bad-index-v is provided, otherwise the [exn:fail:contract](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3acontract%29%29) exception is raised.

Added in version 6.4.0.5 of package base.
Changed in version 7.0.0.10: Added the optional bad-index-v argument.

> ```
(hash-iterate-key+value ht pos)    →    any/c   any/c

  ht : hash?
  pos : exact-nonnegative-integer?

(hash-iterate-key+value ht pos bad-index-v)    →    any/c   any/c

  ht : hash?
  pos : exact-nonnegative-integer?
  bad-index-v : any/c
```
Returns the key and value for the element in ht at index pos.
If pos is not a valid hash index for ht, the result is (values bad-index-v bad-index-v) if bad-index-v is provided, otherwise the exn:fail:contract exception is raised.


# 4.15 Hash Tables
Added in version 6.4.0.5 of package base.
Changed in version 7.0.0.10: Added the optional bad-index-v argument.
> ```
(hash-copy ht)   →   (and/c hash? (not/c immutable?))
  ht : hash?```
Returns a mutable hash table with the same mappings, same key-comparison mode, and same key-holding strength as ht.


#### 4.15.1 Additional Hash Table Functions
|                                                                                |                                                                                |
|:--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------:|
|  ([require](require.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._require%29%29) [racket/hash](#%28mod-path._racket%2Fhash%29)) |  package: [base](https://pkgs.racket-lang.org/package/base "Install this package using `raco pkg install base`") |
The bindings documented in this section are provided by the [racket/hash](#%28mod-path._racket%2Fhash%29) library, not [racket/base](index.html) or [racket](index.html).
> ```
(hash-union ht0
    ht ...
   [ #:combine combine
    #:combine/key combine/key)
  →  (and/c hash? immutable?)
  ht0 : (and/c hash? immutable?)
  ht : hash?
   combine   :   (  →   any/c any/c any/c)
      =   (lambda _ (error 'hash-union ....))
   combine/key   :   (  →   any/c any/c any/c any/c)
      =   (lambda (k a b) (combine a b))


# 4.15 Hash Tables
```
(parameter)	→
(-> and/c hash? (not/c immutable?))```

Computes the union of ht0 with each hash table ht by mutable update, adding each element of each ht to ht0 in turn. For each key k and value v, if a mapping from k to some value v0 already exists, it is replaced with a mapping from k to (combine/key k v0 v).

Examples:

> ```racket
> > ( define h ( make-hash ) )
> > h
> '#hash()
> > ( hash-union! h ( make-immutable-hash ' ( [ 1 one uno ] [ 2 two dos ] ) ) )
> > h
> '#hash((1 . (one uno)) (2 . (two dos)))
> > ( hash-union! h ( make-immutable-hash ' ( [ 1 eins un ] [ 2 zwei deux ] ) ) #:combine/key ( lambda ( k v1 v2 ) ( append v1 v2 ) ) )
> > h
> '#hash((1 . (one uno eins un)) (2 . (two dos zwei deux)))
> ```

> ```
(hash-intersect ht0
    ht ...
   [ #:combine combine
    #:combine/key combine/key)

  →  (and/c hash? immutable?)
  ht0 : (and/c hash? immutable?)
  ht : hash?
   combine   :   (  →   any/c any/c any/c)
      =   (lambda _ (error 'hash-intersect ...))

   combine/key   :   (  →   any/c any/c any/c any/c)
      =   (lambda (k a b) (combine a b))
```


# 4.15 Hash Tables
Constructs the hash table which is the intersection of ht0 with every hash table ht. In the resulting hash table, a key k is mapped to a combination of the values to which k is mapped in each of the hash tables. The final values are computed by stepwise combination of the values appearing in each of the hash tables by applying (combine/key k v vi), where vi is the value to which k is mapped in the i-th hash table ht, and v is the accumulation of the values from the previous steps. The comparison predicate of the first argument (eq?, eqv?, equal-always?, equal?) determines the one for the result.
Examples:
> ```racket
> > ( hash-intersect ( make-immutable-hash ' ( ( a . 1 ) ( b . 2 ) ( c . 3 ) ) ) ( make-immutable-hash ' ( ( a . 4 ) ( b . 5 ) ) ) #:combine + )
> '#hash((a . 5) (b . 7))
> > ( hash-intersect ( make-immutable-hash ' ( ( a . 1 ) ( b . 2 ) ( c . 3 ) ) ) ( make-immutable-hash ' ( ( a . 4 ) ( b . 5 ) ) ) #:combine/key ( lambda ( k v1 v2 ) ( if ( eq? k ' a ) ( + v1 v2 ) ( - v1 v2 ) ) ) )
> '#hash((a . 5) (b . -3))
> ```
Added in version 7.9.0.1 of package base.
> ```
(hash-filter ht pred)   →   hash?
  ht : hash?
  pred : (  →   any/c any/c boolean?)```


# 4.15 Hash Tables
Filters the [hash?](#%28def._%28%28quote._~23~25kernel%29._hash~3f%29%29) ht based on a predicate pred applied to both its keys and values. This function constructs a new hash table that includes only those key-value pairs from the input ht for which the predicate pred returns true when applied simultaneously to the keys and values of ht. The output hash table retains the mutability and the key comparison predicate (e.g., [eqv?](Equality.html#%28def._%28%28quote._~23~25kernel%29._eqv~3f%29%29), [equal-always?](Equality.html#%28def._%28%28quote._~23~25kernel%29._equal-always~3f%29%29), [equal?](Equality.html#%28def._%28%28quote._~23~25kernel%29._equal~3f%29%29)) of the input hash table ht, ensuring that the structural and operational properties of the original hash are preserved in the output.
Examples:
> ```racket
> > ( hash-filter ( for/hash ( [ num ' ( 1 2 3 4 5 ) ] ) ( values num ( * num 2 ) ) ) ( λ ( k v ) ( and ( < k 3 ) ( even? v ) ) ) )> '#hash((1 . 2) (2 . 4))
> > ( hash-filter ( make-hash ) ( λ ( k v ) ( < k 3 ) ) )> '#hash()
> > ( hash-filter ( make-hasheq ' ( [ #f . "false" ] [ #t . "true" ] ) ) ( λ ( k v ) ( and ( eq? k #t ) ( string=? v "true" ) ) ) )
> '#hasheq((#t . "true"))
> > ( hash-filter ( hash ( list 1 2 ) ' pair ( vector 3 4 ) ' vector ) ( λ ( k v ) ( and ( list? k ) ( symbol? v ) ) ) )
> '#hash(((1 2) . pair))
> > ( hash-filter ( hash "one" 1 2 "two" "three" 3 ) ( λ ( k v ) ( and ( not ( number? k ) ) ( number? v ) ( > v 1 ) ) ) )
> '#hash(("three" . 3))
> ```
Added in version 8.13.0.4 of package base.
> ```


# 4.15 Hash Tables
(hash-filter-keys ht pred)  →  hash?
  ht : hash?
  pred : procedure?
```
(parameter)	→```

Filters the [hash?](#%28def._%28%28quote._~23~25kernel%29._hash~3f%29%29) ht based on a predicate pred applied to its values. This function returns a new hash table containing only the key-value pairs for which the predicate pred returns true when applied to the values of ht. The resulting hash table retains the mutability and the key comparison predicate (e.g., [eq?](Equality.html#%28def._%28%28quote._~23~25kernel%29._eq~3f%29%29), [eqv?](Equality.html#%28def._%28%28quote._~23~25kernel%29._eqv~3f%29%29), [equal-always?](Equality.html#%28def._%28%28quote._~23~25kernel%29._equal-always~3f%29%29), [equal?](Equality.html#%28def._%28%28quote._~23~25kernel%29._equal~3f%29%29)) of the input hash table ht.

Examples:

> ```racket
> > ( hash-filter-values ( for/hash ( [ num ' ( 1 2 3 4 5 ) ] ) ( values num num ) ) ( λ ( v ) ( < v 3 ) ) )> '#hash((1 . 1) (2 . 2))
> > ( hash-filter-values ( make-hash ) ( λ ( v ) ( < v 3 ) ) )> '#hash()
> > ( hash-filter-values ( make-hasheqv ' ( [ 1 . "one" ] [ 2 . "two" ] ) ) ( λ ( v ) ( eqv? v "two" ) ) )
> '#hasheqv((2 . "two"))
> > ( hash-filter-values ( hash ' one "1" ' two 2 ' three "3" ) ( lambda ( v ) ( string? v ) ) )
> '#hash((one . "1") (three . "3"))
> > ( hash-filter-values ( hash ' list ( list 1 2 3 ) ' vector # ( 4 5 6 ) ' string "hello" ) ( lambda ( v ) ( vector? v ) ) )
> '#hash((vector . #(4 5 6)))
> > ( hash-filter-values ( hash ' nested-hash ( hash ' a 1 ' b 2 ) ' nested-list ( list ' x ' y ' z ) ) ( lambda ( v ) ( hash? v ) ) )
> '#hash((nested-hash . #hash((a . 1) (b . 2))))
> ```

Added in version 8.12.0.9 of package base.

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

# 4.16 Treelists

8.18.0.13

### 4.16 Treelists

A treelist represents a sequence of elements in a way that supports many operations in O(log N) time: accessing an element of the list by index, adding to the front of the list, adding to the end of the list, removing an element by index, replacing an element by index, appending lists, dropping elements from the start or end of the list, and extracting a sublist. More generally, unless otherwise specified, operations on a treelist of length N take O(log N) time. The base for the log in O(log N) is large enough that it’s effectively constant-time for many purposes. Treelists are currently implemented as RRB trees \[[Stucki15](doc-bibliography.html#%28cite._.Stucki15%29)\].

Treelists are primarily intended to be used in immutable form via [racket/treelist](#%28mod-path._racket%2Ftreelist%29), where an operation such as adding to the treelist produces a new treelist while the old one remains intact. A mutable variant of treelists is provided by [racket/mutable-treelist](#%28mod-path._racket%2Fmutable-treelist%29), where a mutable treelist can be a convenient alternative to putting an immutable treelist into a [box](boxes.html#%28tech._box%29). Mutable treelist operations take the same time as immutable treelist operations, unless otherwise specified. Where the term “treelist” is used by itself, it refers to an immutable treelist.

An immutable or mutable treelist can be used as a single-valued sequence (see [Sequences](sequences.html)). The elements of the list serve as elements of the sequence. See also [in-treelist](#%28def._%28%28lib._racket%2Ftreelist..rkt%29._in-treelist%29%29) and [in-mutable-treelist](#%28def._%28%28lib._racket%2Fmutable-treelist..rkt%29._in-mutable-treelist%29%29). An immutable treelist can also be used as a [stream](streams.html#%28tech._stream%29).

Changed in version 8.15.0.3 of package base: Made treelists serializable.

#### 4.16.1 Immutable Treelists

|                                                                                |                                                                                |
|:----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------:|
|  ([require](require.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._require%29%29) [racket/treelist](#%28mod-path._racket%2Ftreelist%29)) |  package: [base](https://pkgs.racket-lang.org/package/base "Install this package using `raco pkg install base`") |

The bindings documented in this section are provided by the [racket/treelist](#%28mod-path._racket%2Ftreelist%29) library, not [racket/base](index.html) or [racket](index.html).

Added in version 8.12.0.7 of package base.

> ```
(treelist? v)  →  boolean?
  v : any/c
```


# 4.15 Hash Tables
Returns #t if v is a treelist, #f otherwise.
> ```
(treelist v ...) → treelist?
  v : any/c```
Returns a [treelist](#%28tech._treelist%29) with vs as its elements in order.
This operation takes O(N log N) time to construct a treelist of N elements.
Example:
> ```racket
> > ( treelist 1 "a" ' apple )
> (treelist 1 "a" 'apple)
> ```
> ```
(make-treelist size v)  →  treelist?
  size : exact-nonnegative-integer?
  v : any/c
```
Returns a treelist with size size, where every element is v. This operation takes O(log N) time to construct a treelist of N elements.

Examples:

> ```racket
> > ( make-treelist 0 ' pear )
> (treelist)
> > ( make-treelist 3 ' pear )
> (treelist 'pear 'pear 'pear)
> ```

Added in version 8.12.0.11 of package base.

> ```
(treelist-empty? tl)   →   boolean?
  tl : treelist?

value

empty-treelist : (and/c treelist? treelist-empty?)```

A predicate and constant for a [treelist](#%28tech._treelist%29) of length 0.

Although every empty treelist is [equal?](Equality.html#%28def._%28%28quote._~23~25kernel%29._equal~3f%29%29) to [empty-treelist](#%28def._%28%28lib._racket%2Ftreelist..rkt%29._empty-treelist%29%29), since a treelist can be chaperoned via [chaperone-treelist](#%28def._%28%28lib._racket%2Ftreelist..rkt%29._chaperone-treelist%29%29), not every empty treelist is [eq?](Equality.html#%28def._%28%28quote._~23~25kernel%29._eq~3f%29%29) to [empty-treelist](#%28def._%28%28lib._racket%2Ftreelist..rkt%29._empty-treelist%29%29).

> ```
(treelist-length tl)  →  exact-nonnegative-integer?
  tl : treelist?
```


# 4.15 Hash Tables
Returns the number of elements in tl. This operation takes O(1) time.
Examples:
> ```racket
> > ( define items ( treelist 1 "a" ' apple ) )
> > ( treelist-length items )
> 3
> ```
> ```
(treelist-ref tl pos)  →  any/c
  tl : treelist?
  pos : exact-nonnegative-integer?
```

Returns the posth element of tl. The first element is position 0, and the last position is one less than ([treelist-length](#%28def._%28%28lib._racket%2Ftreelist..rkt%29._treelist-length%29%29) tl).

Examples:

> ```racket
> > ( define items ( treelist 1 "a" ' apple ) )
> > ( treelist-ref items 0 )
> 1
> > ( treelist-ref items 2 )
> 'apple
> > ( treelist-ref items 3 )
> treelist-ref: index is out of range
> index: 3
> valid range: [0, 2]
> treelist: (treelist 1 "a" 'apple)
> ```

> ```
(treelist-first tl)  →  any/c
  tl : treelist?

(treelist-last tl)  →  any/c
  tl : treelist?
```
Shorthands for using treelist-ref to access the first or last element of a treelist.
Examples:
> ```racket
> > ( define items ( treelist 1 "a" ' apple ) )
> > ( treelist-first items )
> 1
> > ( treelist-last items )
> 'apple
> ```
> ```
(treelist-insert tl pos v)   →   treelist?
  tl : treelist?
  pos : exact-nonnegative-integer?
  v : any/c```
Produces a treelist like tl, except that v is inserted as an element before the element at pos. If pos is ([treelist-length](#%28def._%28%28lib._racket%2Ftreelist..rkt%29._treelist-length%29%29) tl), then v is added to the end of the treelist.
Examples:


# 4.15 Hash Tables
> ```racket
> > ( define items ( treelist 1 "a" ' apple ) )
> > ( treelist-insert items 1 "alpha" )
> (treelist 1 "alpha" "a" 'apple)
> > ( treelist-insert items 3 "alpha" )
> (treelist 1 "a" 'apple "alpha")
> ```
> ```
(treelist-add tl v)  →  treelist?
  tl : treelist?
  v : any/c
(treelist-cons tl v)  →  treelist?
  tl : treelist?
  v : any/c
```
Shorthands for using treelist-insert to insert at the end or beginning of a treelist.

Although the main operation to extend a pair list is cons to add to the front, treelists are intended to be extended by adding to the end with treelist-add, and treelist-add tends to be faster than treelist-cons.

Examples:

> ```racket
> > ( define items ( treelist 1 "a" ' apple ) )
> > ( treelist-add items "alpha" )
> (treelist 1 "a" 'apple "alpha")
> > ( treelist-cons items "alpha" )
> (treelist "alpha" 1 "a" 'apple)
> ```

> ```
(treelist-delete tl pos)   →   treelist?
  tl : treelist?
  pos : exact-nonnegative-integer?```

Produces a treelist like tl, except that the element at pos is removed.

Examples:

> ```racket
> > ( define items ( treelist 1 "a" ' apple ) )
> > ( treelist-delete items 1 )
> (treelist 1 'apple)
> > ( treelist-delete items 3 )
> treelist-delete: index is out of range
> index: 3
> valid range: [0, 2]
> treelist: (treelist 1 "a" 'apple)
> ```

> ```
(treelist-set tl pos v)  →  treelist?
  tl : treelist?
  pos : exact-nonnegative-integer?
  v : any/c
```


# 4.15 Hash Tables
Produces a treelist like tl, except that the element at pos is replaced with v. The result is equivalent to (treelist-insert (treelist-delete tl pos) pos v).
Examples:
> ```racket
> > ( define items ( treelist 1 "a" ' apple ) )
> > ( treelist-set items 1 "b" )
> (treelist 1 "b" 'apple)
> ```
> ```
(treelist-append tl ...) → treelist?
  tl : treelist?```
Appends the elements of the given tls into a single [treelist](#%28tech._treelist%29). If M treelists are given and the resulting treelist’s length is N, then appending takes O(M log N) time.
Examples:
> ```racket
> > ( define items ( treelist 1 "a" ' apple ) )
> > ( treelist-append items items )
> (treelist 1 "a" 'apple 1 "a" 'apple)
> > ( treelist-append items ( treelist "middle" ) items )
> (treelist 1 "a" 'apple "middle" 1 "a" 'apple)
> ```
> ```
(treelist-take tl n)  →  treelist?
  tl : treelist?
  n : exact-nonnegative-integer?
(treelist-drop tl n)  →  treelist?
  tl : treelist?
  n : exact-nonnegative-integer?
(treelist-take-right tl n)  →  treelist?
  tl : treelist?
  n : exact-nonnegative-integer?
(treelist-drop-right tl n)  →  treelist?
  tl : treelist?
  n : exact-nonnegative-integer?


# 4.15 Hash Tables
```
Produces a treelist like tl but with only the first n elements, without the first n elements, with only the last n elements, or without the last n elements, respectively.

Examples:

> ```racket
> > ( define items ( treelist 1 "a" ' apple ) )
> > ( treelist-take items 2 )
> (treelist 1 "a")
> > ( treelist-drop items 2 )
> (treelist 'apple)
> > ( treelist-take-right items 2 )
> (treelist "a" 'apple)
> > ( treelist-drop-right items 2 )
> (treelist 1)
> ```

> ```
(treelist-sublist tl n m)   →   treelist?
  tl : treelist?
  n : exact-nonnegative-integer?
  m : exact-nonnegative-integer?```

Produces a [treelist](#%28tech._treelist%29) like tl but with only elements at position n (inclusive) through position m (exclusive).

Examples:

> ```racket
> > ( define items ( treelist 1 "a" ' apple ) )
> > ( treelist-sublist items 1 3 )
> (treelist "a" 'apple)
> ```

> ```
(treelist-reverse tl)  →  treelist?
  tl : treelist?
```
Produces a treelist like tl but with its elements reversed, equivalent to using treelist-take to keep 0 elements (but also any chaperone on the treelist) and then adding each element back in reverse order. Reversing takes O(N log N) time.
Examples:
> ```racket
> > ( define items ( treelist 1 "a" ' apple ) )
> > ( treelist-reverse items )
> (treelist 'apple "a" 1)
> ```
> ```
(treelist-rest tl)   →   treelist?
  tl : treelist?```
A shorthand for using [treelist-drop](#%28def._%28%28lib._racket%2Ftreelist..rkt%29._treelist-drop%29%29) to drop the first element of a [treelist](#%28tech._treelist%29).


# 4.15 Hash Tables
The [treelist-rest](#%28def._%28%28lib._racket%2Ftreelist..rkt%29._treelist-rest%29%29) operation is efficient, but not as fast as [rest](pairs.html#%28def._%28%28lib._racket%2Flist..rkt%29._rest%29%29) or [cdr](pairs.html#%28def._%28%28quote._~23~25kernel%29._cdr%29%29). For iterating through a treelist, consider using [treelist-ref](#%28def._%28%28lib._racket%2Ftreelist..rkt%29._treelist-ref%29%29) or a [for](for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%29%29) form with [in-treelist](#%28def._%28%28lib._racket%2Ftreelist..rkt%29._in-treelist%29%29), instead.
Examples:
> ```racket
> > ( define items ( treelist 1 "a" ' apple ) )
> > ( treelist-rest items )
> (treelist "a" 'apple)
> ```
> ```
(treelist  →  vector tl)  →  vector?
  tl : treelist?
(treelist  →  list tl)  →  list?
  tl : treelist?
(vector  →  treelist vec)  →  treelist?
  vec : vector?
(list  →  treelist lst)  →  treelist?
  lst : list?


# 4.15 Hash Tables
```
Convenience functions for converting between treelists, lists, and vectors. Each conversion takes O(N) time.

Examples:

> ```racket
> > ( define items ( list  →  treelist ' ( 1 "a" ' apple ) ) )
> > ( treelist  →  vector items )
> '#(1 "a" 'apple)
> ```

> ```
(treelist-map tl proc)   →   treelist?
  tl : treelist?
  proc : (any/c .  →  . any/c)```

Produces a [treelist](#%28tech._treelist%29) by applying proc to each element of tl and gathering the results into a new treelist. For a constant-time proc, this operation takes O(N) time.

Examples:

> ```racket
> > ( define items ( treelist 1 "a" ' apple ) )
> > ( treelist-map items box )
> (treelist '#&1 '#&"a" '#&apple)
> ```

> ```
(parameter)	→
(-> any/c . → . any)
```
Applies proc to each element of tl, ignoring the results. For a constant-time proc, this operation takes O(N) time.
Examples:
> ```racket
> > ( define items ( treelist 1 "a" ' apple ) )
> > ( treelist-for-each items println )
> 1 "a" 'apple
> ```
> ```
(treelist-filter keep tl)  →  treelist?
  keep : (any/c .  →  . any/c)
  tl : treelist?


# 4.15 Hash Tables
```

Produces a treelist with only members of tl that satisfy keep.

Examples:

> ```racket
> > ( treelist-filter even? ( treelist 1 2 3 2 4 5 2 ) )
> (treelist 2 2 4 2)
> > ( treelist-filter odd? ( treelist 1 2 3 2 4 5 2 ) )
> (treelist 1 3 5)
> > ( treelist-filter ( λ ( x ) ( not ( even? x ) ) ) ( treelist 1 2 3 2 4 5 2 ) )
> (treelist 1 3 5)
> > ( treelist-filter ( λ ( x ) ( not ( odd? x ) ) ) ( treelist 1 2 3 2 4 5 2 ) )
> (treelist 2 2 4 2)
> ```

Added in version 8.15.0.6 of package base.

> ```
(treelist-member? tl v [eql?) → boolean?
  tl : treelist?
  v : any/c
  eql? : (any/c any/c .  →  . any/c) = equal?
```
Checks each element of tl with eql? and v (with v the second argument) until the result is a true value, and then returns #t. If no such element is found, the result is #f. For a constant-time eql?, this operation takes O(N) time.
Examples:
> ```racket
> > ( define items ( treelist 1 "a" ' apple ) )
> > ( treelist-member? items "a" )
> #t
> > ( treelist-member? items 1.0 = )
> #t
> > ( treelist-member? items 2.0 = )
> =: contract violation
> expected: number?
> given: "a"
> ```
> ```
(treelist-find tl pred) → any/c
  tl : treelist?
  pred : (any/c .  →  . any/c)```
Checks each element of tl with pred until the result is a true value, and then returns that element. If no such element is found, the result is #f. For a constant-time pred, this operation takes O(N) time.
Examples:


# 4.15 Hash Tables
> ```racket
> > ( define items ( treelist 1 "a" ' apple ) )
> > ( treelist-find items string? )
> "a"
> > ( treelist-find items symbol? )
> 'apple
> > ( treelist-find items number->string )
> 1
> ```
> ```
(treelist-index-of tl v [eql?)
  →  (or/c exact-nonnegative-integer? #f)
  tl : treelist?
  v : any/c
  eql? : (any/c any/c .  →  . any/c) = equal?
```

Returns the index of the first element in tl that is eql? to v. If no such element is found, the result is #f.

Examples:

> ```racket
> > ( define items ( treelist 1 "a" ' apple ) )
> > ( treelist-index-of items 1 )
> 0
> > ( treelist-index-of items "a" )
> 1
> > ( treelist-index-of items ' apple )
> 2
> > ( treelist-index-of items ' unicorn )
> #f
> ```

Added in version 8.15.0.6 of package base.

> ```
(treelist-flatten v)  →  treelist?
  v : any/c
```
Flattens a tree of nested treelists into a single treelist.
Examples:
> ```racket
> > ( treelist-flatten ( treelist ( treelist "a" ) "b" ( treelist "c" ( treelist "d" ) "e" ) ( treelist ) ) )
> (treelist "a" "b" "c" "d" "e")
> > ( treelist-flatten "a" )
> (treelist "a")
> ```
Added in version 8.15.0.6 of package base.
> ```
(treelist-append* tlotl)  →  treelist?
  tlotl : (treelist/c treelist?)


# 4.15 Hash Tables
```
Appends elements of a treelist of treelists together into one treelist, leaving any further nested treelists alone.

Example:

> ```racket
> > ( treelist-append* ( treelist ( treelist "a" "b" ) ( treelist "c" ( treelist "d" ) "e" ) ( treelist ) ) )
> (treelist "a" "b" "c" (treelist "d") "e")
> ```

Added in version 8.15.0.6 of package base.

> ```
(treelist-sort tl
    less-than?
   [ #:key key
    #:cache-keys? cache-keys?)    →    treelist?

  tl : treelist?
  less-than? : (any/c any/c .  →  . any/c)
  key : (or/c #f (any/c .  →  . any/c)) = #f
  cache-keys? : boolean? = #f```

Like [sort](pairs.html#%28def._%28%28lib._racket%2Fprivate%2Flist..rkt%29._sort%29%29), but operates on a [treelist](#%28tech._treelist%29) to produce a sorted treelist. Sorting takes O(N log N) time.

Examples:

> ```racket
> > ( define items ( treelist "x" "a" "q" ) )
> > ( treelist-sort items string<? )> (treelist "a" "q" "x")
> ```

> ```
(in-treelist tl)  →  sequence?
  tl : treelist?
```
Returns a sequence equivalent to tl.
An in-treelist application can provide better performance for treelist iteration when it appears directly in a for clause.
Examples:
> ```racket
> > ( define items ( treelist "x" "a" "q" ) )
> > ( for/list ( [ e ( in-treelist items ) ] ) ( string-append e "!" ) )
> '("x!" "a!" "q!")
> ```
> ```
(sequence → treelist s) → treelist?
  s : sequence?```
Returns a treelist whose elements are the elements of s, each of which must be a single value. If s is infinite, this function does not terminate.
Examples:


# 4.15 Hash Tables
> ```racket
> > ( sequence->treelist ( list 1 "a" ' apple ) )
> (treelist 1 "a" 'apple)
> > ( sequence->treelist ( vector 1 "a" ' apple ) )
> (treelist 1 "a" 'apple)
> > ( sequence->treelist ( stream 1 "a" ' apple ) )
> (treelist 1 "a" 'apple)
> > ( sequence->treelist ( open-input-bytes ( bytes 1 2 3 4 5 ) ) )
> (treelist 1 2 3 4 5)
> > ( sequence->treelist ( in-range 0 10 ) )
> (treelist 0 1 2 3 4 5 6 7 8 9)
> ```
Added in version 8.15.0.6 of package base.
>
<colgroup><col style="width: 100%" /></colgroup>

<colgroup><col style="width: 100%" /></colgroup>

syntax

([for/treelist](#%28form._%28%28lib._racket%2Ftreelist..rkt%29._for%2Ftreelist%29%29) (for-clause ...) body-or-break ... body)

<colgroup><col style="width: 100%" /></colgroup>

syntax

([for*/treelist](#%28form._%28%28lib._racket%2Ftreelist..rkt%29._for%2A%2Ftreelist%29%29) (for-clause ...) body-or-break ... body)

Like [for/list](for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Flist%29%29) and [for*/list](for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2A%2Flist%29%29), but generating [treelists](#%28tech._treelist%29).
Example:


# 4.15 Hash Tables
> ```racket
> > ( for/treelist ( [ i ( in-range 10 ) ] ) i )
> (treelist 0 1 2 3 4 5 6 7 8 9)
> ```
> ```
(chaperone-treelist tl
    #:state state
   [ #:state-key state-key]
    #:ref ref-proc
    #:set set-proc
    #:insert insert-proc
    #:delete delete-proc
    #:take take-proc
    #:drop drop-proc
    #:append append-proc
    #:prepend prepend-proc
   [ #:append2 append2-proc]
    prop
    prop-val ...
    ...)
  →  (and/c treelist? chaperone?)
  tl : treelist?
  state : any/c
  state-key : any/c = (list 'fresh)
   ref-proc   :   ( treelist? exact-nonnegative-integer? any/c any/c
> .  →  . any/c )
   set-proc   :   ( treelist? exact-nonnegative-integer? any/c any/c
> .  →  . ( values any/c any/c ) )
   insert-proc   :   ( treelist? exact-nonnegative-integer? any/c any/c
> .  →  . ( values any/c any/c ) )
   delete-proc   :   ( treelist? exact-nonnegative-integer? any/c
> .  →  . any/c )
   take-proc   :   ( treelist? exact-nonnegative-integer? any/c
> .  →  . any/c )
   drop-proc   :   ( treelist? exact-nonnegative-integer? any/c
> .  →  . any/c )
   append-proc   :   ( treelist? treelist? any/c
> .  →  . ( values treelist? any/c ) )
   prepend-proc   :   ( treelist? treelist? any/c
> .  →  . ( values treelist? any/c ) )
   append2-proc   :   ( or/c #f ( treelist? treelist? any/c any/c
> .  →  . ( values treelist? any/c any/c ) ) )
      =   #f
  prop : impersonator-property?
  prop-val : any/c


# 4.15 Hash Tables
```
Analogous to chaperone-vector, returns a chaperone of tl, which redirects the treelist-ref, treelist-set, treelist-insert, treelist-append, treelist-delete, treelist-take, and treelist-drop operations, as well as operations derived from those. The state argument is an initial state, where a state value is passed to each procedure that redirects an operation, and except for ref-proc (which corresponds to the one operation that does not update a treelist), a new state is returned to be associated with the updated treelist. When state-key is provided, it can be used with treelist-chaperone-state to extract the state from the original treelist or an updated treelist.

The ref-proc procedure must accept tl, an index passed to treelist-ref, the value that treelist-ref on tl produces for the given index, and the current chaperone state; it must produce a chaperone replacement for the value, which is the result of treelist-ref on the chaperone.

The set-proc procedure must accept tl, an index passed to treelist-set, the value provided to treelist-set, and the current chaperone state; it must produce two values: a chaperone replacement for the value, which is used in the result of treelist-set on the chaperone, and an updated state. The result of treelist-set is chaperoned with the same procedures and properties as tl, but with the updated state.

The insert-proc procedure is like set-proc, but for inserting via treelist-insert.

The delete-proc, take-proc, and drop-proc procedures must accept tl, the index or count for deleting, taking or dropping, and the current chaperone state; they must produce an updated state. The result of treelist-delete, treelist-take, or treelist-drop is chaperoned with the same procedures and properties as tl, but with the updated state.

The append-proc procedure must accept tl, a treelist to append onto tl, and the current chaperone state; it must produce a chaperone replacement for the second treelist, which is appended for the result of treelist-append on the chaperone, and an updated state. The result of treelist-append is chaperoned with the same procedures and properties as tl, but with the updated state.

The prepend-proc procedure must accept a treelist being append with tl, tl, and the current chaperone state; it must produce a chaperone replacement for the first treelist, which is prepended for the result of treelist-append on the chaperone, and an updated state. The result of treelist-append is chaperoned with the same procedures and properties as tl, but with the updated state.

The append2-proc procedure is optional and similar to append-proc, but when it is non-#f, append2-proc is used instead of append-proc when a second argument to treelist-append is chaperoned with the same state-key. In that case, the second argument to append2-proc is the second argument with a state-key chaperone wrapper removed, and with that chaperone’s state as the last argument to append2-proc.

When two chaperoned treelists are given to treelist-append and append2-proc is not used, then the append-proc of the first treelist is used, and the result of append-proc will still be a chaperone whose prepend-proc is used. If the result of prepend-proc is a chaperone, then that chaperone’s append-proc is used, and so on. If prepend-proc and append-proc keep returning chaperones, it is possible that no progress will be made.

Example:

> ```racket
> > ( chaperone-treelist ( treelist 1 "a" ' apple ) #:state ' ignored-state #:ref ( λ ( tl pos v state ) v ) #:set ( λ ( tl pos v state ) ( values v state ) ) #:insert ( λ ( tl pos v state ) ( values v state ) ) #:delete ( λ ( tl pos state ) state ) #:take ( λ ( tl pos state ) state ) #:drop ( λ ( tl pos state ) state ) #:append2 ( λ ( tl other state other-state ) ; or #f ( values other state ) ) #:append ( λ ( tl other state ) ( values other state ) ) #:prepend ( λ ( other tl state ) ( values other state ) ) )
> (treelist 1 "a" 'apple)
> ```

> ```
(treelist-chaperone-state tl
    state-key
   [ fail-k)    →    any/c

  tl : treelist?
  state-key : any/c
  fail-k : (procedure-arity-includes/c 0) = key-error```

Extracts state associated with a treelist chaperone where state-key (compared using [eq?](Equality.html#%28def._%28%28quote._~23~25kernel%29._eq~3f%29%29)) was provided along with the initial state to [chaperone-treelist](#%28def._%28%28lib._racket%2Ftreelist..rkt%29._chaperone-treelist%29%29). If tl is not a chaperone with state keyed by state-key, then fail-k is called, and the default fail-k raises [exn:fail:contract](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3acontract%29%29).

#### 4.16.2 Mutable Treelists

|                                                                                |                                                                                |
|:--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------:|
|  ([require](require.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._require%29%29) [racket/mutable-treelist](#%28mod-path._racket%2Fmutable-treelist%29)) |  package: [base](https://pkgs.racket-lang.org/package/base "Install this package using `raco pkg install base`") |

The bindings documented in this section are provided by the [racket/mutable-treelist](#%28mod-path._racket%2Fmutable-treelist%29) library, not [racket/base](index.html) or [racket](index.html).

A mutable treelist is like an immutable [treelist](#%28tech._treelist%29) in a box, where operations that change the mutable treelist replace the treelist in the box. As a special case, [mutable-treelist-set!](#%28def._%28%28lib._racket%2Fmutable-treelist..rkt%29._mutable-treelist-set%21%29%29) on an unimpersonated mutable treelist modifies the treelist representation within the boxed value. This model of a mutable treelist explains its behavior in the case of concurrent modification: concurrent [mutable-treelist-set!](#%28def._%28%28lib._racket%2Fmutable-treelist..rkt%29._mutable-treelist-set%21%29%29) operations for different positions will not interefere, but races with other operations or on impersonated mutable treelists will sometimes negate one of the modifications. Concurrent modification is thus somewhat unpredictable but still safe, and it is not managed by a lock.

A mutable treelist is not a treelist in the sense of [treelist?](#%28def._%28%28lib._racket%2Ftreelist..rkt%29._treelist~3f%29%29), which recognizes only immutable treelists. Operations on a mutable treelist have the same time complexity as corresponding operations on an immutable treelist unless otherwise noted.

Added in version 8.12.0.7 of package base.

> ```
(mutable-treelist? v)  →  boolean?
  v : any/c
```


# 4.15 Hash Tables
Returns #t if v is a mutable treelist, #f otherwise.
> ```
(mutable-treelist v ...) → mutable-treelist?
  v : any/c```
Returns a [mutable treelist](#%28tech._mutable._treelist%29) with vs as its elements in order.
Example:
> ```racket
> > ( mutable-treelist 1 "a" ' apple )
> (mutable-treelist 1 "a" 'apple)
> ```
> ```
(make-mutable-treelist n [v) → mutable-treelist?
  n : exact-nonnegative-integer?
  v : any/c = #f
```
Creates a mutable treelist that contains n elements, each initialized as v. Creating the mutable treelist takes O(N) time for N elements.

Example:

> ```racket
> > ( make-mutable-treelist 3 "a" )
> (mutable-treelist "a" "a" "a")
> ```

> ```
(treelist-copy tl)   →   mutable-treelist?
  tl : treelist?

(mutable-treelist-copy tl)   →   mutable-treelist?
  tl : mutable-treelist?```

Creates a [mutable treelist](#%28tech._mutable._treelist%29) that contains the same elements as tl. Creating the mutable treelist takes O(N) time for N elements.

Examples:

> ```racket
> > ( treelist-copy ( treelist 3 "a" ) )
> (mutable-treelist 3 "a")
> > ( mutable-treelist-copy ( mutable-treelist 3 "a" ) )
> (mutable-treelist 3 "a")
> ```

> ```
(mutable-treelist-snapshot tl [n m) → treelist?
  tl : mutable-treelist?
  n : exact-nonnegative-integer? = 0
  m : (or/c #f exact-nonnegative-integer?) = #f
```


# 4.15 Hash Tables
Produces an immutable treelist that has the same elements as tl at position n (inclusive) through position m (exclusive). If m is #f, then the length of tl is used, instead. Creating the immutable treelist takes O(N) time for N elements of the resulting treelist, on top of the cost of treelist-sublist if the result is a sublist.
Examples:
> ```racket
> > ( define items ( mutable-treelist 1 "a" ' apple ) )
> > ( define snap ( mutable-treelist-snapshot items ) )
> > snap
> (treelist 1 "a" 'apple)
> > ( mutable-treelist-snapshot items 1 )
> (treelist "a" 'apple)
> > ( mutable-treelist-snapshot items 1 2 )
> (treelist "a")
> > ( mutable-treelist-drop! items 2 )
> > items
> (mutable-treelist 'apple)
> > snap
> (treelist 1 "a" 'apple)
> ```
> ```
(mutable-treelist-empty? tl)   →   boolean?
  tl : mutable-treelist?```
Returns #t for [mutable treelist](#%28tech._mutable._treelist%29) that is currently of length 0, #f otherwise.
> ```
(mutable-treelist-length tl)  →  exact-nonnegative-integer?
  tl : mutable-treelist?
```

Returns the number of elements currently in tl.

Examples:

> ```racket
> > ( define items ( mutable-treelist 1 "a" ' apple ) )
> > ( mutable-treelist-length items )
> 3
> > ( mutable-treelist-add! items ' extra )
> > ( mutable-treelist-length items )
> 4
> ```

> ```
(mutable-treelist-ref tl pos)  →  any/c
  tl : mutable-treelist?
  pos : exact-nonnegative-integer?
```


# 4.15 Hash Tables
Returns the posth element of tl. The first element is position 0, and the last position is one less than ([mutable-treelist-length](#%28def._%28%28lib._racket%2Fmutable-treelist..rkt%29._mutable-treelist-length%29%29) tl).
Examples:
> ```racket
> > ( define items ( mutable-treelist 1 "a" ' apple ) )
> > ( mutable-treelist-ref items 0 )
> 1
> > ( mutable-treelist-ref items 2 )
> 'apple
> > ( mutable-treelist-ref items 3 )
> mutable-treelist-ref: index is out of range
> index: 3
> valid range: [0, 2]
> mutable treelist: (mutable-treelist 1 "a" 'apple)
> ```
> ```
(mutable-treelist-first tl)  →  any/c
  tl : mutable-treelist?
(mutable-treelist-last tl)  →  any/c
  tl : mutable-treelist?
```
(parameter)	→```

Modifies tl to insert v into the list before position pos. If pos is ([mutable-treelist-length](#%28def._%28%28lib._racket%2Fmutable-treelist..rkt%29._mutable-treelist-length%29%29) tl), then v is added to the end of the treelist.

Examples:

> ```racket
> > ( define items ( mutable-treelist 1 "a" ' apple ) )
> > ( mutable-treelist-insert! items 1 "alpha" )
> > items
> (mutable-treelist 1 "alpha" "a" 'apple)
> ```

> ```
(parameter)	→
(-> mutable-treelist-add! tl v)
```
(parameter)	→```
Modifies tl to remove the element at pos.
Examples:
> ```racket
> > ( define items ( mutable-treelist 1 "a" ' apple ) )
> > ( mutable-treelist-delete! items 1 )
> > items
> (mutable-treelist 1 'apple)
> ```
> ```
(parameter)	→


# 4.15 Hash Tables
```
(parameter)	→
(-> or/c treelist? mutable-treelist?)```

Modifies tl by appending or prepending all of the elements of other-tl. If other-tl is a [mutable treelist](#%28tech._mutable._treelist%29), it is first converted to an immutable [treelist](#%28tech._treelist%29) with [mutable-treelist-snapshot](#%28def._%28%28lib._racket%2Fmutable-treelist..rkt%29._mutable-treelist-snapshot%29%29), which takes O(N) time if other-tl has N elements. If other-tl is an immutable treelist but chaperoned, then appending or prepending takes O(N) time for N elements.

Examples:

> ```racket
> > ( define items ( mutable-treelist 1 "a" ' apple ) )
> > ( mutable-treelist-append! items ( treelist ' more ' things ) )
> > items
> (mutable-treelist 1 "a" 'apple 'more 'things)
> > ( mutable-treelist-prepend! items ( treelist 0 "b" ' banana ) )
> > items
> (mutable-treelist 0 "b" 'banana 1 "a" 'apple 'more 'things)
> > ( mutable-treelist-append! items items )
> > items
> (mutable-treelist 0 "b" 'banana 1 "a" 'apple 'more 'things 0 "b" 'banana 1 "a" 'apple 'more 'things)
> ```

Changed in version 8.15.0.11 of package base: Added [mutable-treelist-prepend!](#%28def._%28%28lib._racket%2Fmutable-treelist..rkt%29._mutable-treelist-prepend%21%29%29).

> ```
(parameter)	→
(-> mutable-treelist-drop! tl n)
```
(parameter)	→```
Modifies tl to remove elements other than elements at position n (inclusive) through position m (exclusive).
Examples:


# 4.15 Hash Tables
> ```racket
> > ( define items ( mutable-treelist 1 "a" ' apple ' pie ) )
> > ( mutable-treelist-sublist! items 1 3 )
> > items
> (mutable-treelist "a" 'apple)
> ```
> ```
(parameter)	→
```

Modifies tl to reverse all of its elements.

Examples:

> ```racket
> > ( define items ( mutable-treelist 1 "a" ' apple ' pie ) )
> > ( mutable-treelist-reverse! items )
> > items
> (mutable-treelist 'pie 'apple "a" 1)
> ```

> ```
(mutable-treelist  →  vector tl)  →  vector?
  tl : mutable-treelist?

(mutable-treelist  →  list tl)  →  list?
  tl : mutable-treelist?

(vector  →  mutable-treelist vec)  →  mutable-treelist?
  vec : vector?

(list  →  mutable-treelist lst)  →  mutable-treelist?
  lst : list?
```
Convenience functions for converting between [mutable treelists](#%28tech._mutable._treelist%29), [lists](pairs.html#%28tech._list%29), and [vectors](vectors.html#%28tech._vector%29). Each conversion takes O(N) time.
Examples:
> ```racket
> > ( define items ( list->mutable-treelist ' ( 1 "a" ' apple ) ) )
> > ( mutable-treelist->vector items )
> '#(1 "a" 'apple)
> ```
> ```
(parameter)	→
(-> any/c . → . any/c)


# 4.15 Hash Tables
```
(parameter)	→
(-> any/c . → . any)```

Like [treelist-for-each](#%28def._%28%28lib._racket%2Ftreelist..rkt%29._treelist-for-each%29%29), but for a [mutable treelist](#%28tech._mutable._treelist%29).

Examples:

> ```racket
> > ( define items ( mutable-treelist 1 "a" ' apple ) )
> > ( mutable-treelist-for-each items println )
> 1 "a" 'apple
> ```

> ```
(mutable-treelist-member? tl v [eql?) → boolean?
  tl : mutable-treelist?
  v : any/c
  eql? : (any/c any/c .  →  . any/c) = equal?
```
Like treelist-member?, but for a mutable treelist.
Examples:
> ```racket
> > ( define items ( mutable-treelist 1 "a" ' apple ) )
> > ( mutable-treelist-member? items "a" )
> #t
> > ( mutable-treelist-member? items 1.0 = )
> #t
> ```
> ```
(mutable-treelist-find tl pred) → any/c
  tl : mutable-treelist?
  pred : (any/c .  →  . any/c)```
Like [treelist-find](#%28def._%28%28lib._racket%2Ftreelist..rkt%29._treelist-find%29%29), but for a [mutable treelist](#%28tech._mutable._treelist%29).
Examples:
> ```racket
> > ( define items ( mutable-treelist 1 "a" ' apple ) )
> > ( mutable-treelist-find items string? )
> "a"
> > ( mutable-treelist-find items symbol? )
> 'apple
> ```
> ```
(parameter)	→
(-> any/c any/c . → . any/c)


# 4.15 Hash Tables
```
Like vector-sort!, but operates on a mutable treelist.

Examples:

> ```racket
> > ( define items ( mutable-treelist "x" "a" "q" ) )
> > ( mutable-treelist-sort! items string<? )> > items
> (mutable-treelist "a" "q" "x")
> ```

> ```
(in-mutable-treelist tl)   →   sequence?
  tl : mutable-treelist?```

Returns a [sequence](sequences.html#%28tech._sequence%29) equivalent to tl.

An [in-mutable-treelist](#%28def._%28%28lib._racket%2Fmutable-treelist..rkt%29._in-mutable-treelist%29%29) application can provide better performance for mutable treelist iteration when it appears directly in a [for](for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%29%29) clause.

Examples:

> ```racket
> > ( define items ( mutable-treelist "x" "a" "q" ) )
> > ( for/list ( [ e ( in-mutable-treelist items ) ] ) ( string-append e "!" ) )
> '("x!" "a!" "q!")
> ```

> <table data-cellpadding="0" data-cellspacing="0"><colgroup><col style="width: 100%" /></colgroup><tbody><tr><td><table data-cellpadding="0" data-cellspacing="0"><colgroup><col style="width: 100%" /></colgroup><tbody><tr><td><blockquote>

<p>syntax</p>

<p>([for/mutable-treelist](#%28form._%28%28lib._racket%2Fmutable-treelist..rkt%29._for%2Fmutable-treelist%29%29) maybe-length (for-clause ...) body-or-break ... body)</p></blockquote></td></tr></tbody></table></td></tr><tr><td><table data-cellpadding="0" data-cellspacing="0"><colgroup><col style="width: 100%" /></colgroup><tbody><tr><td><blockquote>

<p>syntax</p>

<p>([for*/mutable-treelist](#%28form._%28%28lib._racket%2Fmutable-treelist..rkt%29._for%2A%2Fmutable-treelist%29%29) maybe-length (for-clause ...) body-or-break ... body)</p></blockquote></td></tr></tbody></table></td></tr></tbody></table>

Like [for/vector](for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Fvector%29%29) and [for*/vector](for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2A%2Fvector%29%29), but generating [mutable treelists](#%28tech._mutable._treelist%29).

Examples:

> ```racket
> > ( for/mutable-treelist ( [ i ( in-range 10 ) ] ) i )
> (mutable-treelist 0 1 2 3 4 5 6 7 8 9)
> > ( for/mutable-treelist #:length 15 ( [ i ( in-range 10 ) ] ) i )
> (mutable-treelist 0 1 2 3 4 5 6 7 8 9 0 0 0 0 0)
> > ( for/mutable-treelist #:length 15 #:fill ' a ( [ i ( in-range 10 ) ] ) i )
> (mutable-treelist 0 1 2 3 4 5 6 7 8 9 'a 'a 'a 'a 'a)
> ```

> ```
(chaperone-mutable-treelist tl
    #:ref ref-proc
    #:set set-proc
    #:insert insert-proc
    #:append append-proc
   [ #:prepend prepend-proc]
    prop
    prop-val ...
    ...)

  →  (and/c mutable-treelist? chaperone?)
  tl : mutable-treelist?
   ref-proc   :   ( mutable-treelist? exact-nonnegative-integer? any/c
> .  →  . any/c )

   set-proc   :   ( mutable-treelist? exact-nonnegative-integer? any/c
> .  →  . any/c )

   insert-proc   :   ( mutable-treelist? exact-nonnegative-integer? any/c
> .  →  . any/c )

   append-proc   :   ( mutable-treelist? treelist?
> .  →  . treelist? )

   prepend-proc   :   ( treelist? mutable-treelist?
> .  →  . treelist? )
      =   (λ (o t) (append-proc t o))

  prop : impersonator-property?
  prop-val : any/c
```


# 4.15 Hash Tables
Similar to chaperone-treelist, but for mutable treelists. For example, the given set-proc is used for mutable-treelist-set!, and the resulting value is installed into the mutable treelist instead of the one provided to set-proc. Mutable treelist chaperones do not have state separate from the treelist itself, and procedures like set-proc do not consume or return a state.
> ```
(impersonate-mutable-treelist tl
    #:ref ref-proc
    #:set set-proc
    #:insert insert-proc
    #:append append-proc
   [ #:prepend prepend-proc]
    prop
    prop-val ...
    ...)
   →   (and/c mutable-treelist? impersonator?)
  tl : mutable-treelist?
   ref-proc   :   ( mutable-treelist? exact-nonnegative-integer? any/c
> .  →  . any/c )
   set-proc   :   ( mutable-treelist? exact-nonnegative-integer? any/c
> .  →  . any/c )
   insert-proc   :   ( mutable-treelist? exact-nonnegative-integer? any/c
> .  →  . any/c )
   append-proc   :   ( mutable-treelist? treelist?
> .  →  . treelist? )
   prepend-proc   :   ( treelist? mutable-treelist?
> .  →  . treelist? )
      =   (λ (o t) (append-proc t o))
  prop : impersonator-property?
  prop-val : any/c```
Like [chaperone-mutable-treelist](#%28def._%28%28lib._racket%2Fmutable-treelist..rkt%29._chaperone-mutable-treelist%29%29), but ref-proc, set-proc, insert-proc, and append-proc are not obligated to produce chaperones.
------------------------------------------------------------------------


# 4.17 Sequences and Streams


### 4.17 Sequences and Streams
[Sequences](sequences.html#%28tech._sequence%29) and [streams](streams.html#%28tech._stream%29) abstract over iteration of elements in a collection. Sequences allow iteration with [for](for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%29%29) macros or with sequence operations such as [sequence-map](sequences.html#%28def._%28%28lib._racket%2Fsequence..rkt%29._sequence-map%29%29). Streams are functional sequences that can be used either in a generic way or a stream-specific way. [Generators](Generators.html#%28tech._generator%29) are closely related stateful objects that can be converted to a sequence and vice-versa.


# 4.17 Sequences and Streams
|                                                                                |
|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
|     [4.17.1 Sequences](sequences.html)                                                                                |
|       [4.17.1.1 Sequence Predicate and Constructors](sequences.html#%28part._.Sequence_.Predicate_and_.Constructors%29)                            |
|       [4.17.1.2 Sequence Conversion](sequences.html#%28part._.Sequence_.Conversion%29)                                                             |
|       [4.17.1.3 Additional Sequence Operations](sequences.html#%28part._more-sequences%29)                                                         |
|         [4.17.1.3.1 Additional Sequence Constructors and Functions](sequences.html#%28part._.Additional_.Sequence_.Constructors_and_.Functions%29) |
|     [4.17.2 Streams](streams.html)                                                                                |
|     [4.17.3 Generators](Generators.html)                                                                                |
------------------------------------------------------------------------


# 4.17.1 Sequences


#### 4.17.1 Sequences
> > > <img src="finger.png" width="24" height="24" alt="+" />[Sequence Constructors](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=guide&rel=for.html%23%2528part._sequences%2529&version=8.18.0.13) in [The Racket Guide](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=guide&rel=index.html&version=8.18.0.13) introduces sequences.
A sequence encapsulates an ordered collection of values. The elements of a sequence can be extracted with one of the [for](for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%29%29) syntactic forms, with the procedures returned by [sequence-generate](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._sequence-generate%29%29), or by converting the sequence into a [stream](streams.html#%28tech._stream%29).
The sequence datatype overlaps with many other datatypes. Among built-in datatypes, the sequence datatype includes the following:
-   exact nonnegative integers (see below)
-   strings (see [Strings](strings.html))
-   byte strings (see [Byte Strings](bytestrings.html))
-   lists (see [Pairs and Lists](pairs.html))
-   mutable lists (see [Mutable Pairs and Lists](mpairs.html))
-   vectors (see [Vectors](vectors.html))
-   flvectors (see [Flonum Vectors](flonums.html#%28part._flvectors%29))
-   fxvectors (see [Fixnum Vectors](fixnums.html#%28part._fxvectors%29))
-   hash tables (see [Hash Tables](hashtables.html))
-   dictionaries (see [Dictionaries](dicts.html))
-   sets (see [Sets](sets.html))


# 4.17.1 Sequences
-   input ports (see [Ports](ports.html))
-   streams (see [Streams](streams.html))
An [exact number](numbers.html#%28tech._exact._number%29) k that is a non-negative [integer](numbers.html#%28tech._integer%29) acts as a sequence similar to ([in-range](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._in-range%29%29) k), except that k by itself is not a [stream](streams.html#%28tech._stream%29).
Custom sequences can be defined using structure type properties. The easiest method to define a custom sequence is to use the [gen:stream](streams.html#%28def._%28%28lib._racket%2Fstream..rkt%29._gen~3astream%29%29) [generic interface](struct-generics.html#%28tech._generic._interface%29). Streams are a suitable abstraction for data structures that are directly iterable. For example, a list is directly iterable with [first](pairs.html#%28def._%28%28lib._racket%2Flist..rkt%29._first%29%29) and [rest](pairs.html#%28def._%28%28lib._racket%2Flist..rkt%29._rest%29%29). On the other hand, vectors are not directly iterable: iteration has to go through an index. For data structures that are not directly iterable, the iterator for the data structure can be defined to be a stream (e.g., a structure containing the index of a vector).
For example, unrolled linked lists (represented as a list of vectors) themselves do not fit the stream abstraction, but have index-based iterators that can be represented as streams:
Examples:


# 4.17.1 Sequences
> ```racket
> > ( struct unrolled-list-iterator ( idx lst ) #:methods gen:stream [ ( define ( stream-empty? iter ) ( define lst ( unrolled-list-iterator-lst iter ) ) ( or ( null? lst ) ( and ( >= ( unrolled-list-iterator-idx iter ) ( vector-length ( first lst ) ) ) ( null? ( rest lst ) ) ) ) ) ( define ( stream-first iter ) ( vector-ref ( first ( unrolled-list-iterator-lst iter ) ) ( unrolled-list-iterator-idx iter ) ) ) ( define ( stream-rest iter ) ( define idx ( unrolled-list-iterator-idx iter ) ) ( define lst ( unrolled-list-iterator-lst iter ) ) ( if ( >= idx ( sub1 ( vector-length ( first lst ) ) ) ) ( unrolled-list-iterator 0 ( rest lst ) ) ( unrolled-list-iterator ( add1 idx ) lst ) ) ) ] )
> > ( define ( make-unrolled-list-iterator ul ) ( unrolled-list-iterator 0 ( unrolled-list-lov ul ) ) )
> > ( struct unrolled-list ( lov ) #:property prop:sequence make-unrolled-list-iterator )
> > ( define ul1 ( unrolled-list ' ( # ( cracker biscuit ) # ( cookie scone ) ) ) )
> > ( for/list ( [ x ul1 ] ) x )
> '(cracker biscuit cookie scone)
> ```


# 4.17.1 Sequences
The [prop:sequence](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._prop~3asequence%29%29) property provides more flexibility in specifying iteration, such as when a pre-processing step is needed to prepare the data for iteration. The [make-do-sequence](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._make-do-sequence%29%29) function creates a sequence given a thunk that returns procedures to implement a sequence, and the [prop:sequence](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._prop~3asequence%29%29) property can be associated with a structure type to implement its implicit conversion to a sequence.


# 4.17.1 Sequences
For most sequence types, extracting elements from a sequence has no side-effect on the original sequence value; for example, extracting the sequence of elements from a list does not change the list. For other sequence types, each extraction implies a side effect; for example, extracting the sequence of bytes from a port causes the bytes to be read from the port. A sequence’s state may either span all uses of the sequence, as for a port, or it may be confined to each distinct time that a sequence is initiated by a [for](for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%29%29) form, [sequence->stream](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._sequence-~3estream%29%29), [sequence-generate](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._sequence-generate%29%29), or [sequence-generate*](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._sequence-generate%2A%29%29). Concretely, the thunk passed to [make-do-sequence](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._make-do-sequence%29%29) is called to [initiate](#%28tech._initiate%29) the sequence each time the sequence is used. Accordingly, different sequences behave differently when they are [initiate](#%28tech._initiate%29)d multiple times.


# 4.17.1 Sequences
> ```racket
> > ( define ( double-initiate s1 ) ; initiate the sequence twice ( define-values ( more?.1 next.1 ) ( sequence-generate s1 ) ) ( define-values ( more?.2 next.2 ) ( sequence-generate s1 ) ) ; alternate fetching from sequence via the two initiations ( list ( next.1 ) ( next.2 ) ( next.1 ) ( next.2 ) ) )
> > ( double-initiate ( open-input-string "abcdef" ) )
> '(97 98 99 100)
> > ( double-initiate ( list 97 98 99 100 ) )
> '(97 97 98 98)
> > ( double-initiate ( in-naturals 97 ) )
> '(97 97 98 98)
> ```
Also, subsequent elements in a sequence may be “consumed” just by calling the first result of [sequence-generate](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._sequence-generate%29%29), even if the second result is never called.
> ```racket
> > ( define ( double-initiate-and-use-more? s1 ) ; initiate the sequence twice ( define-values ( more?.1 next.1 ) ( sequence-generate s1 ) ) ( define-values ( more?.2 next.2 ) ( sequence-generate s1 ) ) ; alternate fetching from sequence via the two initiations ; but this time call `more?` in between ( list ( next.1 ) ( more?.1 ) ( next.2 ) ( more?.2 ) ( next.1 ) ( more?.1 ) ( next.2 ) ( more?.2 ) ) )
> > ( double-initiate-and-use-more? ( open-input-string "abcdef" ) )
> '(97 #t 99 #t 98 #t 100 #t)
> ```
In this example, the state embedded in the first call to [sequence-generate](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._sequence-generate%29%29) “takes” the 98 just by virtue of the invocation of more?.1.


# 4.17.1 Sequences
Individual elements of a sequence typically correspond to single values, but an element may also correspond to multiple values. For example, a hash table generates two values—a key and its value—for each element in the sequence.


##### 4.17.1.1 Sequence Predicate and Constructors
> ```
(sequence? v)  →  boolean?
  v : any/c
```
Returns #t if v can be used as a sequence, #f otherwise.

Examples:

> ```racket
> > ( sequence? 42 )
> #t
> > ( sequence? ' ( a b c ) )
> #t
> > ( sequence? "word" )
> #t
> > ( sequence? #\x )
> #f
> ```

> ```
(in-range end) → stream?
  end : real?
(in-range start end [step)   →   stream?
  start : real?
  end : real?
  step : real? = 1```

Returns a sequence (that is also a [stream](streams.html#%28tech._stream%29)) whose elements are numbers. The single-argument case ([in-range](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._in-range%29%29) end) is equivalent to ([in-range](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._in-range%29%29) 0 end 1). The first number in the sequence is start, and each successive element is generated by adding step to the previous element. The sequence stops before an element that would be greater or equal to end if step is non-negative, or less or equal to end if step is negative.

An [in-range](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._in-range%29%29) application can provide better performance for number iteration when it appears directly in a [for](for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%29%29) clause.

Example: gaussian sum

> ```racket
> > ( for/sum ( [ x ( in-range 10 ) ] ) x )
> 45
> ```

Example: sum of even numbers

> ```racket
> > ( for/sum ( [ x ( in-range 0 100 2 ) ] ) x )
> 2450
> ```

When given zero as step, [in-range](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._in-range%29%29) returns an infinite sequence. It may also return infinite sequences when step is a very small number, and either step or the sequence elements are floating-point numbers.

> ```
(in-inclusive-range start end [step) → stream?
  start : real?
  end : real?
  step : real? = 1
```


# 4.17.1 Sequences
Similar to in-range, but the sequence stopping condition is changed so that the last element is allowed to be equal to end.
An in-inclusive-range application can provide better performance for number iteration when it appears directly in a for clause.
Examples:
> ```racket
> > ( sequence  →  list ( in-inclusive-range 7 11 ) )
> '(7 8 9 10 11)
> > ( sequence  →  list ( in-inclusive-range 7 11 2 ) )
> '(7 9 11)
> > ( sequence  →  list ( in-inclusive-range 7 10 2 ) )
> '(7 9)
> ```
Added in version 8.0.0.13 of package base.
> ```
(in-naturals [start) → stream?
  start : exact-nonnegative-integer? = 0```
Returns an infinite sequence (that is also a [stream](streams.html#%28tech._stream%29)) of exact integers starting with start, where each element is one more than the preceding element.
An [in-naturals](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._in-naturals%29%29) application can provide better performance for integer iteration when it appears directly in a [for](for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%29%29) clause.
Example:
> ```racket
> > ( for/list ( [ k ( in-naturals ) ] [ x ( in-range 10 ) ] ) ( list k x ) )
> '((0 0) (1 1) (2 2) (3 3) (4 4) (5 5) (6 6) (7 7) (8 8) (9 9))
> ```
> ```
(in-list lst)  →  stream?
  lst : list?


# 4.17.1 Sequences
```
Returns a sequence (that is also a stream) that is equivalent to using lst directly as a sequence.

> > > See Pairs and Lists for information on using lists as sequences.

An in-list application can provide better performance for list iteration when it appears directly in a for clause.

See for for information on the reachability of list elements during an iteration.

Example:

> ```racket
> > ( for/list ( [ x ( in-list ' ( 3 1 4 ) ) ] ) ` ( , x , ( * x x ) ) )
> '((3 9) (1 1) (4 16))
> ```

Changed in version 6.7.0.4 of package base: Improved element-reachability guarantee for lists in for.

> ```
(in-mlist mlst) → sequence?
  mlst : mlist?```

Returns a sequence equivalent to mlst. Although the expectation is that mlst is [mutable list](mpairs.html#%28tech._mutable._list%29), [in-mlist](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._in-mlist%29%29) initially checks only whether mlst is a [mutable pair](mpairs.html#%28tech._mutable._pair%29) or [null](pairs.html#%28def._%28%28quote._~23~25kernel%29._null%29%29), since it could change during iteration.

> > > See [Mutable Pairs and Lists](mpairs.html) for information on using mutable lists as sequences.

An [in-mlist](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._in-mlist%29%29) application can provide better performance for mutable list iteration when it appears directly in a [for](for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%29%29) clause.

Example:

> ```racket
> > ( for/list ( [ x ( in-mlist ( mcons "RACKET" ( mcons "LANG" ' ( ) ) ) ) ] ) ( string-length x ) )
> '(6 4)
> ```

> ```
(in-vector vec [start stop step) → sequence?
  vec : vector?
  start : exact-nonnegative-integer? = 0
  stop : (or/c exact-integer? #f) = #f
  step : (and/c exact-integer? (not/c zero?)) = 1
```


# 4.17.1 Sequences
Returns a sequence equivalent to vec when no optional arguments are supplied.
> > > See Vectors for information on using vectors as sequences.
The optional arguments start, stop, and step are analogous to in-range, except that a #f value for stop is equivalent to (vector-length vec). That is, the first element in the sequence is (vector-ref vec start), and each successive element is generated by adding step to index of the previous element. The sequence stops before an index that would be greater or equal to end if step is non-negative, or less or equal to end if step is negative.
If start is not a valid index, then the exn:fail:contract exception is raised, except when start, stop, and (vector-length vec) are equal, in which case the result is an empty sequence.
Examples:
> ```racket
> > ( for ( [ x ( in-vector ( vector 1 ) 1 ) ] ) x )
> > ( for ( [ x ( in-vector ( vector 1 ) 2 ) ] ) x )
> in-vector: starting index is out of range
> starting index: 2
> valid range: [0, 0]
> vector: '#(1)
> > ( for ( [ x ( in-vector ( vector ) 0 0 ) ] ) x )
> > ( for ( [ x ( in-vector ( vector 1 ) 1 1 ) ] ) x )
> ```
If stop is not in \[-1, (vector-length vec)\], then the exn:fail:contract exception is raised.
If start is less than stop and step is negative, then the exn:fail:contract exception is raised. Similarly, if start is more than stop and step is positive, then the exn:fail:contract exception is raised.
An in-vector application can provide better performance for vector iteration when it appears directly in a for clause.
Examples:


# 4.17.1 Sequences
> ```racket
> > ( define ( histogram vector-of-words ) ( define a-hash ( make-hash ) ) ( for ( [ word ( in-vector vector-of-words ) ] ) ( hash-set! a-hash word ( add1 ( hash-ref a-hash word 0 ) ) ) ) a-hash )
> > ( histogram # ( "hello" "world" "hello" "sunshine" ) )
> '#hash(("hello" . 2) ("sunshine" . 1) ("world" . 1))
> ```
> ```
(in-string str [start stop step) → sequence?
  str : string?
  start : exact-nonnegative-integer? = 0
  stop : (or/c exact-integer? #f) = #f
  step : (and/c exact-integer? (not/c zero?)) = 1```
Returns a sequence equivalent to str when no optional arguments are supplied.
> > > See [Strings](strings.html) for information on using strings as sequences.
The optional arguments start, stop, and step are as in [in-vector](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._in-vector%29%29).
An [in-string](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._in-string%29%29) application can provide better performance for string iteration when it appears directly in a [for](for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%29%29) clause.
Examples:
> ```racket
> > ( define ( line-count str ) ( for/sum ( [ ch ( in-string str ) ] ) ( if ( char=? #\newline ch ) 1 0 ) ) )
> > ( line-count "this string\nhas\nthree \nnewlines" )
> 3
> ```
> ```
(in-bytes bstr [start stop step) → sequence?
  bstr : bytes?
  start : exact-nonnegative-integer? = 0
  stop : (or/c exact-integer? #f) = #f
  step : (and/c exact-integer? (not/c zero?)) = 1


# 4.17.1 Sequences
```
(current-input-port)	→
(-> input-port? . → . any/c)```

Returns a sequence whose elements are produced by calling r on in until it produces [eof](port-ops.html#%28def._%28%28quote._~23~25kernel%29._eof%29%29).

> ```
(in-input-port-bytes in)  →  sequence?
  in : input-port?
```
Returns a sequence equivalent to (in-port read-byte in).
> ```
(in-input-port-chars in)   →   sequence?
  in : input-port?```
Returns a sequence whose elements are read as characters from in (equivalent to ([in-port](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._in-port%29%29) [read-char](Byte_and_String_Input.html#%28def._%28%28quote._~23~25kernel%29._read-char%29%29) in)).
> ```
(current-input-port)	→
(-> current-input-port)
```
(p)	→
(-> current-input-port)```

Returns a sequence equivalent to ([in-port](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._in-port%29%29) ([lambda](lambda.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._lambda%29%29) (p) ([read-bytes-line](Byte_and_String_Input.html#%28def._%28%28quote._~23~25kernel%29._read-bytes-line%29%29) p mode)) in). Note that the default mode is 'any, whereas the default mode of [read-bytes-line](Byte_and_String_Input.html#%28def._%28%28quote._~23~25kernel%29._read-bytes-line%29%29) is 'linefeed.

> ```
(in-hash hash)  →  sequence?
  hash : hash?
(in-hash hash bad-index-v)  →  sequence?
  hash : hash?
  bad-index-v : any/c
```
Returns a sequence equivalent to hash, except when bad-index-v is supplied.


# 4.17.1 Sequences
Like hash-map, iteration via in-hash can adapt to certain modifications to a mutable hash table while a traversal is in progress. Keys removes or remapped by the traversing thread have no immediate adverse affects; the change does not affect a traversal if the key has been seen already, otherwise the traversal skips a deleted key or uses the remapped key’s new value.
Other concurrent modifications, including key removal by a different thread, can lead to skipped entries or an exception if an expected entry key was removed before its key or value could be fetched. If bad-index-v is supplied, then bad-index-v is returned as both the key and the value in the case that the hash is modified concurrently so that iteration does not have a valid hash index. Providing bad-index-v is particularly useful when iterating through a hash table with weakly held keys, since entries can be removed asynchronously (i.e., after in-hash has committed to another iteration, but before it can access the entry for the next iteration).
Examples:
> ```racket
> > ( define table ( hash ' a 1 ' b 2 ) )
> > ( for ( [ ( key value ) ( in-hash table ) ] ) ( printf "key: ~a value: ~a\n" key value ) )
> key: b value: 2 key: a value: 1
> ```
> > > See Hash Tables for information on using hash tables as sequences.
Changed in version 7.0.0.10 of package base: Added the optional bad-index-v argument.
Changed in version 8.18.0.11: Strengthened the guarantees about traversal with same-thread modifications to a mutable hash table.
> ```


# 4.17.1 Sequences
(in-hash-keys hash) → sequence?
  hash : hash?
(in-hash-keys hash bad-index-v)   →   sequence?
  hash : hash?
  bad-index-v : any/c```
Returns a sequence whose elements are the keys of hash, using bad-index-v in the same way as [in-hash](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._in-hash%29%29), and with concurrent-modification guarantees analogous to those of [in-hash](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._in-hash%29%29).
Examples:
> ```racket
> > ( define table ( hash ' a 1 ' b 2 ) )
> > ( for ( [ key ( in-hash-keys table ) ] ) ( printf "key: ~a\n" key ) )
> key: b key: a
> ```
Changed in version 7.0.0.10 of package base: Added the optional bad-index-v argument.
Changed in version 8.18.0.11: Strengthened the guarantees about traversal with same-thread modifications to a mutable hash table.
> ```
(in-hash-values hash)  →  sequence?
  hash : hash?
(in-hash-values hash bad-index-v)  →  sequence?
  hash : hash?
  bad-index-v : any/c


# 4.17.1 Sequences
```
Returns a sequence whose elements are the values of hash, using bad-index-v in the same way as in-hash, and with concurrent-modification guarantees analogous to those of in-hash.

Examples:

> ```racket
> > ( define table ( hash ' a 1 ' b 2 ) )
> > ( for ( [ value ( in-hash-values table ) ] ) ( printf "value: ~a\n" value ) )
> value: 2 value: 1
> ```

Changed in version 7.0.0.10 of package base: Added the optional bad-index-v argument.
Changed in version 8.18.0.11: Strengthened the guarantees about traversal with same-thread modifications to a mutable hash table.

> ```
(in-hash-pairs hash) → sequence?
  hash : hash?
(in-hash-pairs hash bad-index-v)   →   sequence?
  hash : hash?
  bad-index-v : any/c```

Returns a sequence whose elements are pairs, each containing a key and its value from hash (as opposed to using hash directly as a sequence to get the key and value as separate values for each element).

The bad-index-v argument, if supplied, is used in the same way as by [in-hash](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._in-hash%29%29). When an invalid index is encountered, the pair in the sequence with have bad-index-v as both its [car](pairs.html#%28def._%28%28quote._~23~25kernel%29._car%29%29) and [cdr](pairs.html#%28def._%28%28quote._~23~25kernel%29._cdr%29%29). The concurrent-modification guarantees for [in-hash-pairs](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._in-hash-pairs%29%29) are analogous to those of [in-hash](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._in-hash%29%29).

Examples:

> ```racket
> > ( define table ( hash ' a 1 ' b 2 ) )
> > ( for ( [ key+value ( in-hash-pairs table ) ] ) ( printf "key and value: ~a\n" key+value ) )
> key and value: (b . 2) key and value: (a . 1)
> ```

Changed in version 7.0.0.10 of package base: Added the optional bad-index-v argument.
Changed in version 8.18.0.11: Strengthened the guarantees about traversal with same-thread modifications to a mutable hash table.

> ```
(in-mutable-hash hash)  →  sequence?
  hash : (and/c hash? (not/c immutable?) hash-strong?)

(in-mutable-hash hash bad-index-v)  →  sequence?
  hash : (and/c hash? (not/c immutable?) hash-strong?)
  bad-index-v : any/c

(in-mutable-hash-keys hash)  →  sequence?
  hash : (and/c hash? (not/c immutable?) hash-strong?)

(in-mutable-hash-keys hash bad-index-v)  →  sequence?
  hash : (and/c hash? (not/c immutable?) hash-strong?)
  bad-index-v : any/c

(in-mutable-hash-values hash)  →  sequence?
  hash : (and/c hash? (not/c immutable?) hash-strong?)

(in-mutable-hash-values hash bad-index-v)  →  sequence?
  hash : (and/c hash? (not/c immutable?) hash-strong?)
  bad-index-v : any/c

(in-mutable-hash-pairs hash)  →  sequence?
  hash : (and/c hash? (not/c immutable?) hash-strong?)

(in-mutable-hash-pairs hash bad-index-v)  →  sequence?
  hash : (and/c hash? (not/c immutable?) hash-strong?)
  bad-index-v : any/c

(in-immutable-hash hash)  →  sequence?
  hash : (and/c hash? immutable?)

(in-immutable-hash hash bad-index-v)  →  sequence?
  hash : (and/c hash? immutable?)
  bad-index-v : any/c

(in-immutable-hash-keys hash)  →  sequence?
  hash : (and/c hash? immutable?)

(in-immutable-hash-keys hash bad-index-v)  →  sequence?
  hash : (and/c hash? immutable?)
  bad-index-v : any/c

(in-immutable-hash-values hash)  →  sequence?
  hash : (and/c hash? immutable?)

(in-immutable-hash-values hash bad-index-v)  →  sequence?
  hash : (and/c hash? immutable?)
  bad-index-v : any/c

(in-immutable-hash-pairs hash)  →  sequence?
  hash : (and/c hash? immutable?)

(in-immutable-hash-pairs hash bad-index-v)  →  sequence?
  hash : (and/c hash? immutable?)
  bad-index-v : any/c

(in-weak-hash hash)  →  sequence?
  hash : (and/c hash? hash-weak?)

(in-weak-hash hash bad-index-v)  →  sequence?
  hash : (and/c hash? hash-weak?)
  bad-index-v : any/c

(in-weak-hash-keys hash)  →  sequence?
  hash : (and/c hash? hash-weak?)

(in-weak-hash-keys hash bad-index-v)  →  sequence?
  hash : (and/c hash? hash-weak?)
  bad-index-v : any/c

(in-weak-hash-values hash)  →  sequence?
  hash : (and/c hash? hash-weak?)

(in-weak-hash-keys hash bad-index-v)  →  sequence?
  hash : (and/c hash? hash-weak?)
  bad-index-v : any/c

(in-weak-hash-pairs hash)  →  sequence?
  hash : (and/c hash? hash-weak?)

(in-weak-hash-pairs hash bad-index-v)  →  sequence?
  hash : (and/c hash? hash-weak?)
  bad-index-v : any/c

(in-ephemeron-hash hash)  →  sequence?
  hash : (and/c hash? hash-ephemeron?)

(in-ephemeron-hash hash bad-index-v)  →  sequence?
  hash : (and/c hash? hash-ephemeron?)
  bad-index-v : any/c

(in-ephemeron-hash-keys hash)  →  sequence?
  hash : (and/c hash? hash-ephemeron?)

(in-ephemeron-hash-keys hash bad-index-v)  →  sequence?
  hash : (and/c hash? hash-ephemeron?)
  bad-index-v : any/c

(in-ephemeron-hash-values hash)  →  sequence?
  hash : (and/c hash? hash-ephemeron?)

(in-ephemeron-hash-keys hash bad-index-v)  →  sequence?
  hash : (and/c hash? hash-ephemeron?)
  bad-index-v : any/c

(in-ephemeron-hash-pairs hash)  →  sequence?
  hash : (and/c hash? hash-ephemeron?)

(in-ephemeron-hash-pairs hash bad-index-v)  →  sequence?
  hash : (and/c hash? hash-ephemeron?)
  bad-index-v : any/c
```


# 4.17.1 Sequences
Sequence constructors for specific kinds of hash tables. These may perform better than the analogous in-hash forms.
Added in version 6.4.0.6 of package base.
Changed in version 7.0.0.10: Added the optional bad-index-v argument.
Changed in version 8.0.0.10: Added ephemeron variants.
> ```
(in-directory [dir use-dir?) → (sequence/c path?)
  dir : (or/c #f path-string?) = #f
   use-dir?   :   ((and/c path? complete-path?) .  →  . any/c)
      =   (lambda (dir-path) #t)```
Returns a sequence that produces all of the paths for files, directories, and links within dir, except for the contents of any directory for which use-dir? returns #f. If dir is not #f, then every produced path starts with dir as its prefix. If dir is #f, then paths in and relative to the current directory are produced.
An [in-directory](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._in-directory%29%29) sequence traverses nested subdirectories recursively (filtered by use-dir?). To generate a sequence that includes only the immediate content of a directory, use the result of [directory-list](Filesystem.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._directory-list%29%29) as a sequence.
The immediate content of each directory is reported as sorted by [path<?](Manipulating_Paths.html#%28def._%28%28quote._~23~25kernel%29._path~3c~3f%29%29), and the content of a subdirectory is reported before subsequent paths within the directory.
Examples:


# 4.17.1 Sequences
> ```racket
> > ( current-directory ( path-only ( collection-file-path "main.rkt" "info" ) ) )
> > ( for/list ( [ f ( in-directory ) ] ) f )
> '(#<path:compiled> #<path:compiled/main_rkt.dep> #<path:compiled/main_rkt.zo> #<path:main.rkt>)
> > ( for/list ( [ f ( in-directory "compiled" ) ] ) f )
> '(#<path:compiled/main_rkt.dep> #<path:compiled/main_rkt.zo>)
> > ( for/list ( [ f ( in-directory #f ( lambda ( p ) ( not ( regexp-match? #rx"compiled" p ) ) ) ) ] ) f )
> '(#<path:compiled> #<path:main.rkt>)
> ```
Changed in version 6.0.0.1 of package base: Added use-dir? argument.
Changed in version 6.6.0.4: Added guarantee of sorted results.
> ```
(in-producer producer) → sequence?
  producer : procedure?
(in-producer producer stop arg ...)  →  sequence?
  producer : procedure?
  stop : any/c
  arg : any/c


# 4.17.1 Sequences
```
Returns a sequence that contains values from sequential calls to producer, which would usually use some state to do its work.

If a stop value is not given, the sequence goes on infinitely, and therefore it is common to use it with a finite sequence or using #:break etc. If a stop value is given, it is used to identify a value that marks the end of the sequence (and the stop value is not included in the sequence); stop can be a predicate that is applied to the results of producer, or it can be a value that is tested against the result of with eq?. (The stop argument must be a predicate if the stop value is itself a function or if producer returns multiple values.)

If additional args are specified, they are passed to every call to producer.

Examples:

> ```racket
> > ( define ( counter ) ( define n 0 ) ( lambda ( [ d 1 ] ) ( set! n ( + d n ) ) n ) )
> > ( for/list ( [ x ( in-producer ( counter ) ) ] [ y ( in-range 4 ) ] ) x )
> '(1 2 3 4)
> > ( for/list ( [ x ( in-producer ( counter ) ) ] #:break ( = x 5 ) ) x )
> '(1 2 3 4)
> > ( for/list ( [ x ( in-producer ( counter ) 5 ) ] ) x )
> '(1 2 3 4)
> > ( for/list ( [ x ( in-producer ( counter ) 5 1/2 ) ] ) x )
> '(1/2 1 3/2 2 5/2 3 7/2 4 9/2)
> > ( for/list ( [ x ( in-producer read eof ( open-input-string "1 2 3" ) ) ] ) x )
> '(1 2 3)
> ```

> ```
(in-value v) → sequence?
  v : any/c```

Returns a sequence that produces a single value: v.

This form is mostly useful for [let](let.html#%28form._%28%28lib._racket%2Fprivate%2Fletstx-scheme..rkt%29._let%29%29)-like bindings in forms such as [for*/list](for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2A%2Flist%29%29)—but a #:do clause form, added more recently, covers many of the same uses.

> ```
(in-indexed seq)  →  sequence?
  seq : sequence?
```


# 4.17.1 Sequences
Returns a sequence where each element has two values: the value produced by seq, and a non-negative exact integer starting with 0. The elements of seq must be single-valued.
Example:
> ```racket
> > ( for ( [ ( ch i ) ( in-indexed "hello" ) ] ) ( printf "The char at position ~a is: ~a\n" i ch ) )
> The char at position 0 is: h The char at position 1 is: e The char at position 2 is: l The char at position 3 is: l The char at position 4 is: o
> ```
> ```
(in-sequences seq ...) → sequence?
  seq : sequence?```
Returns a sequence that is made of all input sequences, one after the other. Each seq is [initiate](#%28tech._initiate%29)d only after the preceding seq is exhausted. If a single seq is provided, then seq is returned; otherwise, the elements of each seq must all have the same number of values.
> ```
(in-cycle seq ...) → sequence?
  seq : sequence?
```
Similar to in-sequences, but the sequences are repeated in an infinite cycle, where each seq is initiated afresh in each iteration. Beware that if no seqs are provided or if all seqs become empty, then the sequence produced by in-cycle never returns when an element is demanded—or even when the sequence is initiated, if all seqs are initially empty.

> ```
(in-parallel seq ...) → sequence?
  seq : sequence?```

Returns a sequence where each element has as many values as the number of supplied seqs; the values, in order, are the values of each seq. The elements of each seq must be single-valued.

> ```
(in-values-sequence seq)  →  sequence?
  seq : sequence?
```


# 4.17.1 Sequences
Returns a sequence that is like seq, but it combines multiple values for each element from seq as a list of elements.
> ```
(in-values*-sequence seq)  →  sequence?
  seq : sequence?
```

Returns a sequence that is like seq, but when an element of seq has multiple values or a single list value, then the values are combined in a list. In other words, [in-values*-sequence](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._in-values%2A-sequence%29%29) is like [in-values-sequence](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._in-values-sequence%29%29), except that non-list, single-valued elements are not wrapped in a list.

> ```
(stop-before seq pred)  →  sequence?
  seq : sequence?
  pred : (any/c .  →  . any)
```
Returns a sequence that contains the elements of seq (which must be single-valued), but only until the last element for which applying pred to the element produces #t, after which the sequence ends.
> ```
(stop-after seq pred)  →  sequence?
  seq : sequence?
  pred : (any/c .  →  . any)


# 4.17.1 Sequences
```

Returns a sequence that contains the elements of seq (which must be single-valued), but only until the element (inclusive) for which applying pred to the element produces #t, after which the sequence ends.

> ```
(make-do-sequence thunk) → sequence?
   thunk   :   ( or/c (  →  ( values ( any/c .  →  . any )
> ( any/c .  →  . any/c )
> any/c
> ( or/c ( any/c .  →  . any/c ) #f )
> ( or/c ( any/c ... .  →  . any/c ) #f )
> ( or/c ( any/c any/c ... .  →  . any/c ) #f ) ) )
> (  →  ( values ( any/c .  →  . any )
> ( or/c ( any/c .  →  . any/c ) #f )
> ( any/c .  →  . any/c )
> any/c
> ( or/c ( any/c .  →  . any/c ) #f )
> ( or/c ( any/c ... .  →  . any/c ) #f )
> ( or/c ( any/c any/c ... .  →  . any/c ) #f ) ) ) )
```
Returns a sequence whose elements are generated according to thunk.
The sequence is initiated when thunk is called. The initiated sequence is defined in terms of a position, which is initialized to init-pos, and the element, which may consist of multiple values.
The thunk procedure must return either six or seven values. However, use initiate-sequence to return these multiple values, as opposed to listing the values directly.
If thunk returns six values:
-  The first result is a pos  →  element procedure that takes the current position and returns the value(s) for the current element.
-  The second result is a next-pos procedure that takes the current position and returns the next position.
-  The third result is a init-pos value, which is the initial position.


# 4.17.1 Sequences
-  The fourth result is a continue-with-pos? function that takes the current position and returns a true result if the sequence includes the value(s) for the current position, and false if the sequence should end instead of including the value(s). Alternatively, continue-with-pos? can be #f to indicate that the sequence should always include the current value(s). This function is checked on each position before pos  →  element is used.
-  The fifth result is a continue-with-val? function that is like continue-with-pos?, but it takes the current element value(s) as arguments instead of the current position. Alternatively, continue-with-val? can be #f to indicate that the sequence should always include the value(s) at the current position.
-  The sixth result is a continue-after-pos+val? procedure that takes both the current position and the current element value(s) and determines whether the sequence ends after the current element is already included in the sequence. Alternatively, continue-after-pos+val? can be #f to indicate that the sequence can always continue after the current value(s).
If thunk returns seven values, the first result is still the pos  →  element procedure. However, the second result is now an early-next-pos procedure that is described further below. Alternatively, early-next-pos can be #f, which is equivalent to the identity function. Other results’ positions are shifted by one, so the third result is now next-pos, and the fourth result is now init-pos, etc.