Scala return boolean with if else

So, I have to run the following script:

 def check(): Boolean = {
    for ((digit1,digit2,digit3) <- SetOfDigits){
      if ((1,2,5) == (digit1,digit2,digit3))
        true
      else
        false
}
  }

val SetOfDigits = Set((0,2,3),(1,5,6),(7,10,2),(1,2,5))

Now the problem is that the function should return a boolean, but always tell me what return type is here Unit? The function must go through SetOfDigits, and if it finds something equal, how (1,2,5)should it return true else false? Has anyone answered this problem and what should I do to get it working?

+4
source share
4 answers

I do not agree with the decision of Mr. B., I would prefer that you change your implementation, which seems like a very banal way of handling things:

scala> val SetOfDigits = Set((0,2,3),(1,5,6),(7,10,2),(1,2,5))
SetOfDigits: scala.collection.immutable.Set[(Int, Int, Int)] = Set((0,2,3), (1,5,6), (7,10,2), (1,2,5))

scala>   SetOfDigits.contains((1, 2, 5))
res0: Boolean = true

scala>   SetOfDigits.contains((1, 2, 4))
res1: Boolean = false

contains , , false, , .

, forAll contains:

scala> val setOfDigits1 = Set((0,2,3),(1,5,6),(7,10,2),(1,2,5)).flatMap { case(a,b,c) => Set(a,b,c)}
setOfDigits1: scala.collection.immutable.Set[Int] = Set(0, 5, 10, 1, 6, 2, 7, 3)

scala>   val setOfDigits2 =  Set(1,2,3,16,20,7)
setOfDigits2: scala.collection.immutable.Set[Int] = Set(20, 1, 2, 7, 3, 16)

scala>   val setOfDigits3 =  Set(1,2,3,10)
setOfDigits3: scala.collection.immutable.Set[Int] = Set(1, 2, 3, 10)

scala>   setOfDigits2.forall(i => setOfDigits1.contains(i))
res8: Boolean = false

scala>   setOfDigits3.forall(i => setOfDigits1.contains(i))
res9: Boolean = true

, List[(Int, Int, Int)] List[Int], forAll , , contains .

+8

return true false, .

yield ( )

. , , , :

def check(): Boolean = {
    val s = for ((digit1,digit2,digit3) <- SetOfDigits) {
      if ((1,2,5) == (digit1,digit2,digit3))
        return true
    }
    false
  }
+3

, if-else, Unit. @EndeNeu API,

xs.exists( _ == (1,2,5) )
Boolean = true

.

, , setOfDigits setOfDigits, .

+2

Ende Neu.

, , . return.

def check(): Boolean = {
  var found = false
  for ((digit1,digit2,digit3) <- SetOfDigits if !found) {
    if ((1,2,5) == (digit1,digit2,digit3)) found = true
  }
  found
}
+2

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


All Articles