Beautiful Racket: Importing & exporting
A structure type is a user-defined data structure with an arbitrary number of fields. Like a hash table, a structure type allows access to its fields by name. Like a vector, the number of fields is fixed by the structure-type definition.
The struct form defines the structure type itself, and also manufactures a predicate, plus getters (and, for mutable structure types, setters) for each field. The #:transparent option makes the structure type printable in the REPL:
(struct style (color size weight) #:transparent #:mutable)
(define s (style "red" 42 'bold))
s ; (style "red" 42 'bold)
(style? s) ; #t
(style-color s) ; "red"
(set-style-color! s "blue")
(style-color s) ; "blue"
(struct style (color size weight) #:transparent #:mutable) (define s (style "red" 42 'bold)) s ; (style "red" 42 'bold) (style? s) ; #t (style-color s) ; "red" (set-style-color! s "blue") (style-color s) ; "blue" |
It’s not uncommon for a Racketeer to throw some values into a list as a quick-and-dirty data structure. But for anything that will be used more than once, a structure type is better:
-
The getters and setters have readable names.
-
The structure type can have fields added to its definition without changing existing references.
-
An instance of a structure type is represented as a single object in memory, so it can be passed around a program “by reference” (meaning, it’s not duplicated if passed from one function to another).
-
A structure type has its own unique predicate, which can be efficiently tested (say, inside a contract).
The disadvantage of a structure type is that it’s a distinct data type from a hash table, vector, or list, so it can’t be directly used with library functions that consume those types. There’s a little more housekeeping to get values in & out.
-
Programmer-Defined Datatypes in the Racket Guide
-
Structure Types in the Racket Reference