I have the following program: (Scala 2.9.2, Java6)
object Forcomp {
def main(args: Array[String]): Unit = {
val xs = List(-1, 0, 1)
val xss = for (a <- xs; b <- xs if a != 0 && b != 0) yield (a,b)
println(xss)
}
}
It produces this output: List((-1,-1), (-1,1), (1,-1), (1,1))
I would have expected it to only filter out values where a
and b
are both 0 – not all values where either a
or b
are 0.
I can get the behaviour I want by changing the if-clause to this: if (a,b) != (0,0)
– however, should I really have to? Is this a bug or is this intentional behaviour? I, for one, was surprised by this.
The truth table for the filter you have is this:
a==0 | b==0 | (a!=0 && b!=0)
--------------------------------
0 | 0 | 0
0 | 1 | 0
1 | 0 | 0
1 | 1 | 1
whereas the behaviour you say you want is:
a==0 | b==0 | !(a==0 && b==0)
--------------------------------
0 | 0 | 0
0 | 1 | 1
1 | 0 | 1
1 | 1 | 1