What is the most efficient functional version of the following imperative code?
- by justin.r.s.
I'm learning Scala and I want to know the best way of expressing this imperative pattern using Scala's functional programming capabilities.
def f(l: List[Int]): Boolean = {
for (e <- l) {
if (test(e))
return true
}
}
return false
}
The best I can come up with is along the lines of:
l map { e => test(e) } contains true
But this is less efficient since it calls test() on each element, whereas the imperative version stops on the first element that satisfies test(). Is there a more idiomatic functional programming technique I can use to the same effect? The imperative version seems awkward in Scala.