Thomas
07/19/2024, 2:02 AMinline fun for4d(di: Iterable<Int>, ci: Iterable<Int>, bi: Iterable<Int>, ai: Iterable<Int>, block: (d:Int, c:Int, b: Int, a: Int) -> Unit) {
for (d in di){for (c in ci){for (b in bi) {for (a in ai) {
block(d, c, b, a)
}}}}
}
Then we could do:
fun main() {
for4d(1..9, 0..9, 0..9, 0..9){i,j,k,l->
//all 4 digit decimal numbers
println("$i$j$k$l")
}
}
Advantages:
1. Reduces the code indentation depth
2. Easier to type than multiple for loops; saving keystrokes for the round and curly bracket characters, "for"s and "in"s
Limitations:
1. Only supports "for each element" use cases; does not support "for each dimension/row/column"Huib Donkers
07/19/2024, 8:12 AMfor(list in cartesianProduct(1..9, 0..9, 0..9, 0..9))
. Add destructuring and you can get for((i, j, k, l) in cartesianProduct(1..9, 0..9, 0..9, 0..9))
See example here: https://pl.kotl.in/PM8HK5cCT
Based on this stackoverflow answer which goes into a bit more detail (but focusses on sets rather than iterables)Thomas
07/23/2024, 2:23 AMinline fun <A, B> loop2d(bi: Iterable<B>, ai: Iterable<A>, block: (b: B, a: A) -> Unit) {
for (b in bi) for (a in ai) block(b, a)
}
inline fun <A, B, C> loop3d(ci: Iterable<C>, bi: Iterable<B>, ai: Iterable<A>, block: (c: C, b: B, a: A) -> Unit) {
for (c in ci) for (b in bi) for (a in ai) block(c, b, a)
}
inline fun <A, B, C, D> loop4d(di: Iterable<D>, ci: Iterable<C>, bi: Iterable<B>, ai: Iterable<A>, block: (d: D, c: C, b: B, a: A) -> Unit) {
for (d in di) for (c in ci) for (b in bi) for (a in ai) block(d, c, b, a)
}
Huib Donkers
07/23/2024, 1:33 PMHuib Donkers
07/23/2024, 1:39 PMloop
. That makes it feel a bit more generic than it actually is when using it 🙂Thomas
07/23/2024, 1:51 PM