4
votes

I'm having trouble with a nested for loop and using yield properly.

The problem is if I have two lists of the form List[(Int,Int)]

val ls = (1,5)::(3,2)::(5,3)::Nil
val ls_two = (1,9)::(5,9)::(6,7)::Nil

and now I want to create a third list only combining the key and both second int of all the lists so the result would be

val result = (1,5,9)::(5,3,9)::Nil

I've tried a few variations of something like this which none seem to work

val result = for(i <- ls) {
               for(j <- ls_two) {
                 if(i._1 == j._1) yield (i._1,i._2,j._2)
               }
             }

I've tried placing the yield at the end of the for loop, it seems to work if i replace yield with println but i'm not sure how to do it with yield.

Also if you have a more functional approach to how to solve this it would be greatly appreciated, thanks!

1

1 Answers

6
votes

The recommended approach here is not to "nest" the "loops" at all - but to create a single for-comprehension which uses a "guard":

val result = for {
  i <- ls
  j <- ls_two if i._1 == j._1
} yield (i._1,i._2,j._2)