What are some ideas for expressing this function in ‘idiomatic’ Scala. Or more precisely, is there a way to remove the local vars without sacrificing readability?
def solve(threshold: Int)(f: Int => Int): Int = {
var sum = 0
var curr = 0
while(sum < threshold) {
sum += f(curr)
curr += 1
}
curr
}
The only thing I could come up with was this, but it’s longer and less readable in my opinion.
def solve2(threshold: Int)(f: Int => Int): Int = {
val resultIterator = Iterator.iterate (0, 0) { case (curr, sum) =>
(curr + 1, sum + f(curr))
}
(resultIterator find (_._2 >= threshold)).get._1
}
The most direct approach is to turn the while loop into a nested tail-recursive function.
This is the standard “functional” way of looping.