https://github.com/xdavidliu/fun-problems/blob/main/zipper-t...
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...
It's the API that makes something impossible to misuse, and they could offer the same API like List.create(x: T, xs: T[]), but the first one is simpler.
sevensor•2h ago
agentultra•2h ago