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

I am learning Scala and I want to find out the best way to express this imperative pattern using Scala programming functionality.

def f(l: List[Int]): Boolean = {
  for (e <- l) {
    if (test(e))
      return true
    }
  }
  return false
}

The best I can think of are the following lines:

l map { e => test(e) } contains true

But this is less efficient, since it calls test () for each element, while the imperative version stops at the first element that satisfies test (). Is there a more idiomatic method of functional programming that I can use with the same effect? This version seems inconvenient in Scala.

+3
source share
3 answers

You can use the exists method:

val listWithEvens = List(1,2,3,4)
val listWithoutEvens = List(1,3,5)
def test(e: Int) = e % 2 == 0

listWithEvens.exists(test(_)) // true
listWithoutEvens.exists(test(_)) // false

// alternative
listWithEvens.exists(_ % 2 == 0)  // true 

_, :

listWithEvens.exists(v => v % 2 == 0)
+17

, exists (l.exists(test)), , . :

def f(l: List[Int]): Boolean = l.foldLeft(false)((flag, n) => flag || test(n))

, l, , flag . ( ) . , , , , , , , .

, , , exists , - :

def f(l: List[Int]): Boolean = l.dropWhile(!test(_)).nonEmpty
+7

, ( , Scala exists - , , map break ), List () .

import scala.annotation.tailrec

@tailrec
def exists(l: List[Int], p: (Int) => Boolean): Boolean = l match {
  case Nil => false
  case x :: xs => p(x) || exists(xs, p)
}

|| , false , .

, , , .

+1

Source: https://habr.com/ru/post/1781938/


All Articles