Subscript and more complex objects #749
Replies: 0 comments 6 replies
-
Good question! There are two answers. The first is that the iterator model that you describe might not be the best abstraction to use in a world of value semantics. Iterators break value independence, which causes hard problems to solve. Consider this example in C++, which exposes undefined behavior. template<typename T>
auto foo(vector<T> const& a, vector<T> const& b) {
return (rand() % 2 == 0) ? a.begin() : b.begin();
}
int main() {
vector a = { 1, 2, 3 };
auto it = foo(a, { 4, 5, 6 });
cout << *it << endl; // UB
} This program is wrong because I didn't carefully consider the lifetimes of the iterator returned by Swift, for example, uses a different model. Every collection has an index type representing positions in that collection. You can get indices from methods like
The second answer is that Val does in fact have a mechanism to "hold a reference" to the iterated object. We do not call this mechanism a reference, though, because in Val we prefer to think of a span as a projection of some collection. Instead, we use the term "remote part".
|
Beta Was this translation helpful? Give feedback.
-
From reading the docs it seems that subscripts are a way to automate selecting (or yielding) one of its inputs or a subobject thereof, and a call to it basically inlines the selection logic into the caller. Since the returned "selection" is not a first-class concept in the language, i wonder how one would go to implement a data structure that references the original object, like
Deque
type backed by a circular array buffer. Creating aDequeSpan
to represent a subsection of the deque would again require a reference to the deque object, as the elements would not necessarily be layed out contiguously inside the buffer.Beta Was this translation helpful? Give feedback.
All reactions