How could I refactor this code so squaring stops o...
# announcements
e
How could I refactor this code so squaring stops once the first square greater than 10 is found?
Copy code
println((1..100000).map { it * it }.filter { it > 10 }.first())
(My real code doesn’t involve numbers or squaring, just a calculation that I want to stop computing when I get an acceptable result from
map
.)
Even better would be a way I could get a pair with the number from the first list and the squared value satisfying the predicate.
s
Copy code
val firstSquareGreaterThanTen = (1..10000).asSequence()
    .map { it to it * it }
    .first { (_, square) -> square > 10 }

val (base, square) = firstSquareGreaterThanTen
println("base: $base, square: $square")
e
Thanks, @Shawn!
👍 1
a
the question sounded more like a request for
takeWhile
than
first
🤔
1