► |  | The Racket Reference

1 | Language Model
2 | Notation for Documentation
3 | Syntactic Forms
4 | Datatypes
5 | Structures
6 | Classes and Objects
7 | Units
8 | Contracts
9 | Pattern Matching
10 | Control Flow
11 | Concurrency and Parallelism
12 | Macros
13 | Input and Output
14 | Reflection and Security
15 | Operating System
16 | Memory Management
17 | Unsafe Operations
18 | Running Racket
| Bibliography
| Index

▼ | 5 | Structures

5.1 | Defining Structure Types: struct
5.2 | Creating Structure Types
5.3 | Structure Type Properties
5.4 | Generic Interfaces
5.5 | Copying and Updating Structures
5.6 | Structure Utilities
5.7 | Structure Type Transformer Binding

On this page:

struct-copy

top ← prev up next →

#### 5.5`` Copying and Updating Structures

> syntax (struct-copy id struct-expr fld-id ...)
> fld-id |  | = |  | [field-id expr]
> |  | | |  | [field-id #:parent parent-id expr]

Creates a new instance of the structure type id with the same field values as the structure produced by struct-expr, except that the value of each supplied field-id is instead determined by the corresponding expr. If #:parent is specified, the parent-id must be bound to a parent structure type of id.

The id must have a transformer binding that encapsulates information about a structure type (i.e., like the initial identifier bound by struct), and the binding must supply a constructor, a predicate, and all field accessors.

Each field-id is combined with id (or parent-id, if present) to form id-field-id (using the lexical context of field-id), which must be one of the accessor bindings in id. The accessor bindings determined by different field-ids must be distinct. The order of the field-ids need not match the order of the corresponding fields in the structure type.

The struct-expr is evaluated first. The result must be an instance of the id structure type, otherwise the exn:fail:contract exception is raised. Next, the field exprs are evaluated in order (even if the fields that correspond to the field-ids are in a different order). Finally, the new structure instance is created.

The result of struct-expr can be an instance of a sub-type of id, but the resulting copy is an immediate instance of id (not the sub-type).

Examples:
> > (struct fish (color weight) #:transparent)
> > (define marlin (fish 'orange-and-white 11))
> > (define dory (struct-copy fish marlin
> [color 'blue]))
> > dory
> (fish 'blue 11)
> > (struct shark fish (weeks-since-eating-fish) #:transparent)
> > (define bruce (shark 'grey 110 3))
> > (define chum (struct-copy shark bruce
> [weight #:parent fish 90]
> [weeks-since-eating-fish 0]))
> > chum
> (shark 'grey 90 0)
> ; subtypes can be copied as if they were supertypes,
> ; but the result is an instance of the supertype
> > (define not-really-chum
> (struct-copy fish bruce
> [weight 90]))
> > not-really-chum
> (fish 'grey 90)

top ← prev up next →