Search code examples
scalafor-comprehension

Scala: .take(1) in for-comprehension?


val SumABC = 1000
val Max = 468
val Min = 32

val p9 = for {
  a <- Max to 250 by -1
  b <- Min+(Max-a) to 249
  if a*a+b*b == (SumABC-a-b)*(SumABC-a-b)
} yield a*b*(SumABC-a-b)

Can I .take(1) here? (I tried to translate it to flatmap, filter, etc, but since I failed I guess it wouldn't be as readable anyway...)


Solution

  • If I understood your cryptic questin, what you would like to do is the following

    val p9 = (for {
      a <- Max to 250 by -1
      b <- Min+(Max-a) to 249
      if a*a+b*b == (SumABC-a-b)*(SumABC-a-b)
    } yield a*b*(SumABC-a-b)).take(1)
    

    Just add parenthesis before for and after yield to ensure the take method is called on the result of the for block