Tuesday, July 8, 2008

QuickCheck puzzle: the answer

Some time ago I mentioned a problem I've run into with QuickCheck: the following code, intended for generation of non-zero random vectors, does not terminate:

nonzero :: Gen Vec
nonzero = do
  v <- arbitrary
  if norm v > 0 then return v else nonzero

Now it's time to give the answer to this puzzle, which was found by Dmitry Astapov (ADEpt). Test data generators have an implicit size parameter, which is passed down in monadic computation. So if we got zero size, we will always get zero vectors -- "arbitrary" vectors with components from interval [0;0]. So, solution may look like

nonzero = do
  v <- arbitrary
  if norm v > 0 then return v else resize 1 nonzero

No comments: