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.
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)
, exists (l.exists(test)), , . :
exists
l.exists(test)
def f(l: List[Int]): Boolean = l.foldLeft(false)((flag, n) => flag || test(n))
, l, , flag . ( ) . , , , , , , , .
l
flag
, , , exists , - :
def f(l: List[Int]): Boolean = l.dropWhile(!test(_)).nonEmpty
, ( , Scala exists - , , map break ), List () .
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 , .
||
false
, , , .
Source: https://habr.com/ru/post/1781938/More articles:https://translate.googleusercontent.com/translate_c?depth=1&pto=aue&rurl=translate.google.com&sl=ru&sp=nmt4&tl=en&u=https://fooobar.com/questions/1781933/things-one-needs-to-know-while-writing-a-game-engine&usg=ALkJrhhG_W-LygNnvNhllhZr0CY-Cs6i0gwhat is the best subscription based billing system for rails 3? - ruby-on-rails-3JavaScript - jQuery: how to create an array element based on a string - javascriptHow to disable general parameter parsing in PowerShell functions? - powershellDisable an empty option in Django ModelForm - djangoHow to create a YouTube or eBay interface for iPad? - iosTinyMCE - buggy / unusable in IE8 - jqueryrun Ruby / EventMachine script as a system service - ruby | fooobar.comUse jQuery to scroll to the end - jqueryMake concurrent web requests in Java - javaAll Articles