"Flexvector" vs adding "capacity" to "vector"
Erik Dominikus 12 Oct 2020 14:39 UTC
Dear SRFI-214 subscribers,
I would like to share another route I took a few days ago (what a
coincidence!) to achieve the same goal (having a dynamic array) in my
not-yet-but-aspiring-to-be-Scheme implementation.
It is possible to make vectors resizable while maintaining backward
compatibility with Scheme, by adding the concept of "capacity" to
"vector".
In my implementation, a vector has content, capacity, and size:
typedef struct {
Id* con; // array of Scheme object identifiers
int cap; // maximum length before error or reallocation
int siz; // effective length returned by vector-length
} Vec;
Each vector can grow or shrink as much as it likes, as long as its
size does not exceed its capacity. If it has to grow above its
capacity, it signals an error or reallocates its content.
Its advantages compared to flexvectors:
- It subsumes Scheme vectors, so it is backward-compatible with
existing Scheme code: just set siz = cap = the length of the vector.
- It does not define a new type, so it does not raise difficult
questions about subtyping, nomenclature, name-prefixing,
comparison/ordering, etc.
Its disadvantages compared to flexvectors:
- It requires changing the layer below Scheme, although the change
should be small if the underlying layer does not assume that vector
contents cannot move.
- Perhaps not everyone can afford that change.
Thank you.
Best regards,
Erik