Colton Idle
06/29/2023, 7:30 PMouterList.forEach { outerItem ->
innerList.forEach { innterItem ->
Sam
06/29/2023, 7:34 PMflatMap
on a Sequence
is one general pattern for expressing this sort of nested loop without the nestingSam
06/29/2023, 7:34 PMouterList.asSequence().flatMap { innerList.asSequence() }.forEach { ... }
Not sure it's exactly simpler, though...Landry Norris
06/29/2023, 7:40 PMColton Idle
06/29/2023, 7:43 PMColton Idle
06/29/2023, 7:46 PMouterList.forEach { outerItem ->
innerList.forEach { innerItem ->
if (outerItem.blah()) {
set.put(outerItem)
if (innerItem.foo()) { return "something" }
}
Colton Idle
06/29/2023, 7:47 PMLandry Norris
06/29/2023, 7:51 PMColton Idle
06/29/2023, 7:57 PMLandry Norris
06/29/2023, 7:57 PMouterList.filter { it.blah() }
and the return value be innerList.first { it.foo() }
? Unless there's a relationship between them that was omitted for brevity, you may not need the nested loop.Landry Norris
06/29/2023, 8:03 PMJacob
06/29/2023, 8:46 PMfor(outerItem in outerList.filter{it.blah()}){}
Klitos Kyriacou
06/29/2023, 9:08 PMouterList.asSequence().flatMap { innerList.asSequence() }.forEach { ... }
unfortunately just produces outerList.size
copies of innerList
items. To get the actual Cartesian product, you need something like this:
outerList.asSequence().flatMap { outer ->
innerList.asSequence().map { inner ->
outer to inner
}
}
.forEach { (outer, inner) ->
...
}
which unfortunately doesn't save you any indent depth.ephemient
06/30/2023, 2:47 AMchooseAll {
val x = choose(0, 3, 6)
val y = choose(0, 1, 2)
println("$x + $y = ${x + y}")
}
0 + 0 = 0
0 + 1 = 1
0 + 2 = 2
3 + 0 = 3
3 + 1 = 4
3 + 2 = 5
6 + 0 = 6
6 + 1 = 7
6 + 2 = 8
ephemient
06/30/2023, 3:03 AMsequence_ $ do
x <- [0, 3, 6]
y <- [0, 1, 2]
pure $ printf "%d + %d = %d\n" x y (x + y)
in Kotlin… unfortunately can't statically guarantee the lack of side-effects in Kotlin, unlike Haskell)ephemient
06/30/2023, 3:59 AMfor {
x <- 0 to 6 by 3
y <- 0 to 2
} println(s"$x + $y = ${x + y}")
I wonder if anyone has proposed adding similar to KotlinRiccardo Lippolis
06/30/2023, 5:32 AM