如何编写“用于多个范围的元组”?

时间:2019-11-05 14:07:12

标签: kotlin

例如:

for ((x, y) in (1..100, 50 downTo 0)) {}
for ((x, y, z) in (1..100, 50 downTo 0, 500..1000 step 2)) {}

我已经找到了kotlin官方文档:Destructuring Declarations,但仍然无法编写正确的代码。

1 个答案:

答案 0 :(得分:1)

您可以创建一个zipOf函数,该函数返回所有可能组合的Sequence。这是此函数的3个重载:

fun <T1, T2> zipOf(first: Iterable<T1>, second: Iterable<T2>) = sequence {
    for (t1 in first)
        for (t2 in second)
            yield(t1 to t2)
}

fun <T1, T2, T3> zipOf(first: Iterable<T1>, second: Iterable<T2>, third: Iterable<T3>) = sequence {
    for (t1 in first)
        for (t2 in second)
            for (t3 in third)
                yield(Triple(t1, t2, t3))
}

fun <T> zipOf(vararg iterables: Iterable<T>): Sequence<List<T>> =
    iterables.fold(sequenceOf(emptyList())) { result, iterable ->
        result.flatMap { list -> iterable.asSequence().map { elm -> list + elm } }
    }

您可以像这样使用它们:

for ((x, y) in zipOf(1..100, 50 downTo 0)) {}
for ((x, y, z) in zipOf(1..100, 50 downTo 0, 500..1000 step 2)) {}
for ((x, y, z, w) in zipOf(1..100, 50 downTo 0, 500..1000 step 2, 0..1)) {}