Reputation: 1388
In Scala, what if I have a nested for loop, and I want to execute different things on each one.
for (int i = 0; i<5; i++) {
System.out.println(i); //do something for just i
for(int j = 0; j<5; j++) {
System.out.println(i+j); //do something for both i and j
}
}
But the scala code:
for {i<-0 to 5
j<- 0 to 5} yield { print(i); print(i+j)}
gives the output:
0
(0,0)
0
(0,1)
0
(0,2)
0
(0,3)
0
(0,4)
0
(0,5)
but I want it to be:
0
(0,0)
(0,1)
(0,2)
(0,3)
(0,4)
(0,5)
Is there a way to only print i
for each i
, and i+j
for each i
and j
in ONE for loop?
Upvotes: 0
Views: 94
Reputation: 51271
The compiler rewrites for
comprehensions into their constituent map()
, flatMap()
, foreach()
, and withFilter()
parts. That's why some of the normal rules of Scala syntax don't apply inside sequence comprehension expressions. They get mangled in the rewriting process.
There are a few tricks to get around the problem.
for {
i <- 0 to 5
_ = println(i)
j <- 0 to 5
} yield // do stuff with i and j
It really depends on what you need to do with the i
value. It could be that a for
comprehension is not the best tool for the job.
Upvotes: 3
Reputation: 41957
Alternative way of doing the same would be to use map
function as following
val loop = 0 to 5
loop.map(i => {
println(i) // do your stuffs as you did for i
loop.map(j => {
println(i, j) //do your stuffs as you did for i, j
})
})
Upvotes: 1
Reputation: 1397
I think this will do the trick:
(0 to 5).zip(0 to 5).foreach{case (i, j) =>
//do stuff to i an dj
}
Upvotes: 1