What is the most efficient functional version of the following imperative code?

Posted by justin.r.s. on Stack Overflow See other posts from Stack Overflow or by justin.r.s.
Published on 2010-12-24T02:13:06Z Indexed on 2010/12/24 11:54 UTC
Read the original article Hit count: 205

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.

© Stack Overflow or respective owner

Related posts about scala

Related posts about functional-programming