You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
We have to define which traits will be required by for loops to describe how iteration is implemented.
I believe there are two kinds of for loops we want to consider: non-consuming and consuming. Non-consuming loops only need read and/or write access to container being iterated over. That information is described by the introducer of the element pattern, which should be let or inout:
public fun main() {
var a: Array = [1, 2, 3]
for inout x in &a { &x = x * x }
print(a) // [1, 4, 9]
}
Consuming loops take ownership of the container's elements. They use a var or sink let introducer:
public fun main() {
var a: Array = [1, 2, 3]
var b = Array<Int>()
for sink let x in a { &b.append(x) }
// <- `a` is considered consumed here, accessing it causes a compile-time error
}
I think we should a different trait for each of these use cases. For non-consuming loops, Collection is probably the most appropriate choice. A for loop would desugar as a while loop breaking when we reach end_index. For example (desugared parts marked with //*):
public fun main() {
var a: Array = [1, 2, 3]
var i = a.start_index() // *
while i != a.end_index() { // *
inout x = &a[i] // *
&x = x * x
&i = a.index(after: i) // *
}
}
For consuming loops, I think we would need some kind of generator. We can re-use Swift's Sequence (or something similar to get a generator):
public fun main() {
var a: Array = [1, 2, 3]
var b = Array<Int>()
var i = a.make_iterator() // * (note: `make_iterator` is a `sink` method)
while sink let x: Int = &i.next() { // *
&b.append(x)
}
}
The text was updated successfully, but these errors were encountered:
We have to define which traits will be required by for loops to describe how iteration is implemented.
I believe there are two kinds of for loops we want to consider: non-consuming and consuming. Non-consuming loops only need read and/or write access to container being iterated over. That information is described by the introducer of the element pattern, which should be
let
orinout
:Consuming loops take ownership of the container's elements. They use a
var
orsink let
introducer:I think we should a different trait for each of these use cases. For non-consuming loops,
Collection
is probably the most appropriate choice. A for loop would desugar as a while loop breaking when we reachend_index
. For example (desugared parts marked with//*
):For consuming loops, I think we would need some kind of generator. We can re-use Swift's
Sequence
(or something similar to get a generator):The text was updated successfully, but these errors were encountered: