Search code examples
scalascalacheck

for expressions filter doesn't filter anything


This is a for comprehension (or for expressions) that unexpectedly doesn't work at all : the filter have no effect

Just trying to reduce the range of random int of two

Please help

import java.lang.Math.abs
import org.scalacheck._
import Arbitrary._

object Main extends App {
  lazy val minus2Int : Gen[Int] = for {
         int1 <- arbitrary[Int]
         if (abs(int1) < 2147483645)
      } yield int1
  println(minus2Int.sample)
  println(minus2Int.sample)
  println(minus2Int.sample)
}

In the book it is mention :

If the match succeeds, the variables in the pattern get bound to the corresponding parts of the element, just the way it is described in Chapter 15. But if the match fails, no MatchError is thrown. Instead, the element is simply discarded from the iteration.


Solution

  • You're code is trying to filter out 5 values. On the top, 2147483646 and 2147483647 (Int.MaxValue), and on the bottom, -2147483646, -2147483647, and -2147483648 (Int.MinValue). So why does -2147483648 (Int.MinValue) keep showing up?

    It's because there is no Int value +2147483648. Since abs(-2147483648) can't be expressed as a positive value it actually returns the negative value, i.e. the same Int.MinValue value, which is less than 2147483645 so it is not filtered out.