Vector Struct: Performant Fake Structs
(require vector-struct) | package: vector-struct |
This module provides utilities for "faking" structs using vectors. In Racket, struct allocation can be expensive, while vectors are relatively cheap. Since the complex featureset of structs is often unnecessary, this module allows using vectors while still having the convenience of the basic struct API to aid in clarity.
For a version of this module that is compatible with Typed Racket, see typed/vector-struct.
1 Examples
Using this library is mostly equivalent to using ordinary structs. To create a structure type, use the vecstruct form.
(vecstruct point (x y))
Just like ordinary structs, this will create a point function to serve as the struct constructor, and it will also define point-x and point-y accessors.
(define p (point 4 5)) (point-x p) ; => 4 (point-y p) ; => 5
You can also create mutable structs using the #:mutable keyword.
(vecstruct mpoint (x y) #:mutable)
This will generate the corresponding set-point-x! and set-point-y! mutators.
The vecstruct form also creates a predicate function (e.g. point?), which can be used to test for values. Note that a properly-formed vector will pass this test, but vecstruct puts a symbol corresponding to the vector name as the first element of the vector to help identify well-formed values.
2 API
syntax
(vecstruct id (field-id ...) struct-option ...)
struct-option = #:mutable
Subsequently generates a series of id-field-id accessors. If #:mutable is specified, also generates set-id-field-id! mutators.
If #:mutable is specified, then the underlying datatype will be a mutable vector, otherwise it will be an immutable vector.