I am working on creating iterators, for strings, lists, trees, graphs, and potentially other things.
First a side note.
I have a string data type in my engine. The string is implemented as a bunch of small chunks separated physically in memory, let's say 256-byte chunks. So a single string might look like this in memory.
asdfasdfasd...256
[something else]
[something else]
fasdfasdfasdf
So the final string would be:
asdfasdfasd...256fasdfasdfasdf
However, when in code, I want to access the string like this:
string[10]
for (char in string) {
// ...
}
Basically, it feels like a simple array.
But when you access a character in string, it has to have some context. It needs to know which chunk we are currently on, the length of chunks, and if another chunk follows this current chunk. There's a lot under the hood of for (char in string)
.
Given that, I was thinking of having an iterator implement this. But the first part of my confusion is how much should go into the iterator, vs. how much should go into some generic looper/api that takes the iterator as an argument.
For example.
iterator.iterate(function(item, index){
})
The iterator does everything. This would mean, if we were implementing "graph traversal", there would be an entire graph traversal algorithm in the iterator, and it would take a graph as input. This would mean that we could have multiple different iterators like a DFS and a BFS iterator, etc.
But we could instead have it split between the iterator and the outside syntax:
for (item, index in iterator.next()) {
// ...
}
This seems like what you see more often, but it seems to make implementation harder as the state is now split between the external environment and the iterator. Maybe not though.
The reason for asking is because there are these cases:
- while loop
- for loop
- get item at index like
string[10]
- get item by name (hashtable)
- etc.
It seems that if you want to have a generic API to iterating these things, or accessing these properties, you need an abstraction layer like the iterator on top of it. Wondering if that is true, or if not, what options there are.
iterator
for a graph search/traversal task, iterators are understood to provide 1-dimensional travel. Aniterator
on a graph would be expected to return all nodes in no particular order.IEnumerable
from the .NET world? They provide a very reasonable iterator model, you may consider to learn from it.