"coordinate" iteration, e.g `(0 to 0)..(1 to 1)` i...
# stdlib
h
"coordinate" iteration, e.g
(0 to 0)..(1 to 1)
iterates through
0 to 0, 0 to 1, 1 to 0, 1 to 1
. Might be a stretch, but I think it's intuitive.
Copy code
operator fun Pair<Int, Int>.rangeTo(that: Pair<Int, Int>) = object : Iterable<Pair<Int, Int>> {
    override fun iterator() = object : Iterator<Pair<Int, Int>> {
        var i = this@rangeTo.first
        var j = this@rangeTo.second
        
        val m = that.first - i
        val n = that.second - j

        override fun hasNext() = i <= m && j <= n

        override fun next(): Pair<Int, Int> {
            val res = i to j
            
            if (j == n) {
                j = 0
                i++
            } else {
                j++
            }
            
            return res
        }
    }
}
could also be expanded to higher dimensions with
List<Int>.rangeTo(other: List<Int>)
,
IntArray
, etc
d
If anything, this should be a separate type, and I dont think it deserves a place in the stdlib atm. At least it may be difficult to collect all use cases under the same name if so.
h
Yeah, it's more appropriate for a
Vector
type, which Kotlin does not have
d
Kotlin has
data class
which partially covers the use case of
Vector
k
I'd be happier with a general Cartesian product instead of only for ranges
So
(0..1) cart (0..1)
but it would also work for other iterables.
h
yeah, but i do think that the rangeTo operator is a great operator for cartesian product. If they add cartesian product, anyone can create the operator function that calls it should they choose to
Copy code
operator fun <T> Iterable<T>.rangeTo(other: Iterable<T>) = this cart other
k
I don't really get what you're saying.
d
Hes saying he doesn't mind your idea because he can declare his own operator delegating it
k
Huh so he wants
..
to represent cartesian product? Isn't that something different from the code sample, where
..
is a kind of specific range-cartesian on pairs?
h
ah, yeah