Scala For-Comprehension Advanced usage

Let’s say we want to find all three-pair additions that equate to 10 (order is irrelevant so we don’t want dups). What we would normally do in imperative Java would be 3 nested for loops with indexes say i, j and k where i ranges from 1 till 10, j starts from i+1 and k starts from j+1. The body of the for loop would be the if predicate case. We would also need a variable to store the results.

Instead in Scala:


val l = List(1,2,3,4,5,6,7,8,9,10)

for {
   (a,i) <- l.zipWithIndex
   (b,j) <- l.zipWithIndex.drop(i+1)
      c  <- l.drop(j+1)
   if 10 == a + b + c
} println(s"$a $b $c") 

We can also use for comprehension with yield as a returned assignable result rather than println

Advertisements