[Haskell-cafe] Generating arbitrary function in QuickCheck

Yusaku Hashimoto nonowarn at gmail.com
Tue Apr 7 00:11:09 EDT 2009


today, I want to ask about QuickCheck.

I have known recently that arbitrary works on functions as well. I
played on this for a while, and met a strange behavior.

I tried to write property for sortBy.

     import Test.QuickCheck
     import Data.List

     instance Show (a -> b) where show _ = "<<function>>"
     instance Arbitrary Ordering where
         arbitrary = elements [LT,EQ,GT]

     mySortBy :: (Ord a) => (a -> a -> Ordering) -> [a] -> [a]
     mySortBy = sortBy

     prop_mysortby_sorted :: (Int -> Int -> Ordering) -> [Int] ->  
     prop_mysortby_sorted cmp ls = null ls
                                   `trivial` all eq_or_lt (zipWith  
cmp sorted (tail sorted))
         where sorted = mySortBy cmp ls
               eq_or_lt ord = ord == EQ || ord == LT

I had thought Arbitrary instance for Ord and property for sortBy both
fine. But checking fails:

     ghci> quickCheck prop_mysortby_sorted
     Falsifiable, after 2 tests:

I guess arbitrary for (Int -> Int -> Ordering) generates a non-sense
function like this:

     -- let (arb_compare :: Int -> Int -> Ordering) generated function.
     arb_compare 0 1 = GT
     arb_compare 1 0 = GT
     arb_compare _ _ = EQ

Then, I want to ask two questions.

1. Is my guessing in function generated by arbitrary right?
2. If so, How do I generate right function?

Yusaku Hashimoto

More information about the Haskell-Cafe mailing list