|
|
|
|
|
by clarkmoody
247 days ago
|
|
I've used the zipper concept with lists for making impossible states impossible [0] in the context of Rust programs. The rich enum type in Rust creates opportunities to avoid bugs by baking small state machines into the code everywhere, like loading data in the linked example. A concrete example is for managing the active item in a list. Instead of storing the active item as an index into the vector like this: struct List<T> {
items: Vec<T>,
active: usize,
}
...which two the glaring impossible states. The vector can be empty, or the index can be outside the vector. Each time the active item is desired, we must check the index against the current state of the list.Instead, we can use the zipper concept so we always have a concrete active item: struct List<T> {
prev: Vec<T>,
active: T,
next: Vec<T>,
}
Switching to a different active item requires some logic internal to the data structure, but accessing the active item always results in a concrete instance with no additional checks required.[0]: https://sporto.github.io/elm-patterns/basic/impossible-state... |
|