5.5 Copying and Updating Structures (original) (raw)

5.5 Copying and Updating Structures🔗

(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 (which is defined via astructure type defining form such as struct) 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 #:parentis 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 must correspond to a field-id in the structure type defining forms of id(or parent-id, if present). The accessor bindings determined by differentfield-ids under the same id (or parent-id, if present) must be distinct. The order of thefield-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 theexn:fail:contract exception is raised. Next, the field exprs are evaluated in order (even if the fields that correspond to thefield-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 ofid, but the resulting copy is an immediate instance ofid (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)