jeff
08/17/2022, 7:41 PMval seq: Sequence<Int> = ...
seq.takeWhile { it < 100 }.forEach { println("small: $it") }
seq.drop(???).takeWhile { it < 200 }.forEach { println("medium: $it") }
seq.drop(???).forEach { it < 300 }.forEach { println("large: $it" }
but I’m wondering if there’s something more idiomatic/elegant than the `drop()`s. I tried having the Sequence maintain the same iterator, but that skips the items for which the takeWhile {}
returns false (because next()
is called regardless). Any ideas?ephemient
08/17/2022, 9:13 PMval (small, notSmall) = seq.partition { it < 100 }
val (medium, large) = notSmall.partition { it < 200 }
but more lazily?Oliver.O
08/17/2022, 9:30 PMval seq = sequenceOf(1, 110, 210, 2, 310, 3)
seq.groupBy {
if (it < 100) "small" else (if (it < 200) "medium" else "large")
}.forEach { category, values ->
for (value in values)
println("$category: $value")
}
Oliver.O
08/17/2022, 9:34 PMval seq = sequenceOf(1, 110, 210, 2, 310, 3)
seq.groupBy {
when (it) {
in 0 until 100 -> "small"
in 100 until 200 -> "medium"
else -> "large"
}
}.forEach { category, values ->
for (value in values)
println("$category: $value")
}
ephemient
08/17/2022, 10:07 PMtakeWhile
is lazier than `groupBy`; it doesn't require consuming the entire sequence to produce the first valueephemient
08/17/2022, 10:10 PMseq.groupingBy { ... }
to maintain some laziness, but it still has different behavior than the original due to its behavior w.r.t. orderingephemient
08/17/2022, 10:11 PMephemient
08/17/2022, 10:11 PMOliver.O
08/17/2022, 10:58 PM