for (i <- Range(1,7); j <- Range(1,7))
yield (i,j) // want to yield only if there is no such a pair
Is it possible to have access to the list, formed by yield, inside the loop?
For example, if I don’t want to add duplicates.
P.S. The main question is not how to do it in this particular case. But how to avoid duplicates in more complex case, where I want to check, what was already yielded.
You cannot access members of an immutable collection being built from within the for comprehension.
First of all, I’m going to modify your example so it actually produces duplicates:
For comprehensions are just syntactic sugar, so here’s the equivalent using
mapandflatMapthat produces the exact same resultAs you can see, you’re not actually building a single collection, but rather a collection of collections, and then merging them together as they’re created. The inner
mapis taking eachjin the range and mapping it to a pair, then the outerflatMapis mapping eachito a sequence of pairs and merging them together. If I change theflatMapto justmap, the result is this:So only after the whole operation is finished can you access the result as a single collection. The result is a Vector which extends
IndexedSeq[(Int, Int)], so you can use any of that trait’s methods on the result, one of them isdistinct: