define-struct
in Dr(Adapted from notes by Dan Grossman for CSE341.)
Traditional Scheme does not have a standard way of creating new types or modules. Scheme programmers have long used functions to write programs in terms of higher-level abstractions like tree nodes, but underneath everything is still a list.
Over time, several Scheme dialects have extended the language to provide user-defined
types in various ways. Here we take a brief look at a mechanism provided
in Racket. To use it, you need to use DrRacket's Choose Language
command
to select "Pretty Big".
The special form define-struct
declares a new type by giving
the name of the type and its fields. For example,
we can create a type to describe playing cards with
(define-struct card (suit value))
In addition to introducing the type card
, define-struct
introduces
several new bindings.
(make-card s v)
creates a new card
value
with the given arguments (like cons
).(card? x)
that takes one argument and returns #t
only
for arguments made from the corresponding constructor (like cons?
).(card-suit c) (card-value c)
that take
one argument and return the corresponding field, or generate an error if
the argument was
not made from the corresponding constructor (like car
, cdr
).(set-card-suit! c s) (set-card-value! c s)
that mutate
field contents (like set-car!
, set-cdr!
)define-struct
is not exactly a function and is not a Scheme macro
(which we haven't talked about). The key difference is that values built from
the constructor cause every other type predicate (including all the built-in
ones like pair?
) to return #f
. So it is not just
a surface syntax for an underlying list.