A blog that documents my efforts to learn the Haskell programming language.

Wednesday, March 30, 2011

Playing Around with QuickCheck

So I saw the new parallel monad and I wanted to give it a spin. A simple package that factors numbers seemed to be just the thing. It parallelizes nicely. More about that in the companion post -- this post is about my first steps with QuickCheck I wanted to test this factor code:

The first lesson I learned along the way is that the result of a QuickCheck test is a Property, not a Bool; just a heads-up for other newbies. BTW, one of my favorite things about Real World Haskell is that it gives more than a passing thought to stuff like Cabal and QuickCheck.

The test machinery was rather more involved than the code itself. First I had to put together a list of prime numbers, then I could write code that would test factorization over primes and over products of two primes.

This is all straightforward. Getting the final piece of test code took rather more time, but it refactored down to

testDepth = 8 -- actually N-1

check :: Integer -> [Integer] -> Integer -> [Integer] -> Bool

check 0 _ _ _ = True

check y xs n ns =

let p = getPrime (1 + abs(fromIntegral $ head xs))

ps = factors p

p_list = build_assoc_list ns ps

in factors (n*p) == p_list &&
check (y-1) (tail xs) (n*p) (p_list)

prop_complex z zs = z > 0 &&

(fromIntegral $ length zs) >=
(fromIntegral (z `mod` testDepth)) ==>

check (z `mod` testDepth) zs 1 [1]

This works, though I've got to say that the prop_complex check on the length of zs is not exactly elegant. I'd love to hear comments on how to make it more idiomatic Haskell (and that applies to all the code).

Followers

About The Learner

I have 20 years' experience in software development in scientific computing and aerospace, most of it in C or C++ on various Unix platforms. I also have some real industry experience in Lisp, and that led to my interest in Haskell.