Haskell Laws & Testing
Type classes like Functor, Monoid and Monad come with laws: equations every instance must satisfy. The compiler can't check them, so they are a promise. Haskell programmers check such promises, and ordinary business rules too, with property-based testing: instead of a few hand-picked examples, you state a property that must hold for all inputs and let a tool try hundreds of generated ones.
The laws you have met
| Class | Law |
|---|---|
Semigroup |
associativity: (a <> b) <> c == a <> (b <> c) |
Monoid |
identity: mempty <> a == a and a <> mempty == a |
Functor |
fmap id == id, fmap (f . g) == fmap f . fmap g |
Applicative |
pure id <*> v == v (plus three more) |
Monad |
return a >>= f == f a, m >>= return == m, associativity of >>= |
Eq |
reflexive, symmetric, transitive |
Ord |
consistent with Eq, transitive |
Laws are what let you refactor with confidence: if fmap obeys the composition law, then map f . map g can always be replaced by map (f . g), one pass instead of two.
Property-based testing with QuickCheck
The standard tool is QuickCheck (a Hackage package, so it's not available in the playground). You write properties as ordinary functions returning Bool:
import Test.QuickCheck
prop_reverseTwice :: [Int] -> Bool
prop_reverseTwice xs = reverse (reverse xs) == xs
prop_appendAssoc :: [Int] -> [Int] -> [Int] -> Bool
prop_appendAssoc a b c = (a <> b) <> c == a <> (b <> c)
prop_sortIdempotent :: [Int] -> Bool
prop_sortIdempotent xs = sort (sort xs) == sort xs
main :: IO ()
main = do
quickCheck prop_reverseTwice
quickCheck prop_appendAssoc
quickCheck prop_sortIdempotent+++ OK, passed 100 tests.
+++ OK, passed 100 tests.
+++ OK, passed 100 tests.QuickCheck generates random inputs from the argument types (via its Arbitrary class). When a property fails, it shrinks the counterexample to a minimal one, which makes debugging much easier:
ghci> quickCheck (\xs -> reverse xs == (xs :: [Int]))
*** Failed! Falsified (after 3 tests and 2 shrinks):
[0,1]In a Cabal project you add QuickCheck (and often the hspec or tasty test framework) to the build-depends of a test-suite section and run cabal test.
A tiny property checker you can run here
The idea behind QuickCheck fits in a few lines. This checker uses a deterministic pseudo-random generator (so the output is the same on every run), generates 200 random lists, and reports the first counterexample:
import Data.List (sort)
-- deterministic pseudo-random numbers (linear congruential generator)
randoms :: Int -> [Int]
randoms seed = tail (iterate (\s -> (1103515245 * s + 12345) `mod` 2147483648) seed)
-- turn the random stream into test lists of length 0..9 with values -50..49
testLists :: Int -> [[Int]]
testLists seed = go (randoms seed)
where
go (n : rest) =
let len = n `mod` 10
(vals, rest') = splitAt len rest
in map (\v -> v `mod` 100 - 50) vals : go rest'
go [] = []
check :: String -> ([Int] -> Bool) -> IO ()
check name prop =
case filter (not . prop) (take 200 (testLists 42)) of
[] -> putStrLn (name ++ ": OK, passed 200 tests")
(bad : _) -> putStrLn (name ++ ": FAILED for " ++ show bad)
main :: IO ()
main = do
check "reverse twice" (\xs -> reverse (reverse xs) == xs)
check "sort is idempotent" (\xs -> sort (sort xs) == sort xs)
check "length of sort" (\xs -> length (sort xs) == length xs)
check "sum of map (*2)" (\xs -> sum (map (* 2) xs) == 2 * sum xs)
check "reverse is identity" (\xs -> reverse xs == xs)reverse twice: OK, passed 200 tests
sort is idempotent: OK, passed 200 tests
length of sort: OK, passed 200 tests
sum of map (*2): OK, passed 200 tests
reverse is identity: FAILED for [14,3,-44,-15,-18,-17,16]
The last property is false, and the checker found a counterexample, though a long, noisy one. This is exactly why QuickCheck shrinks: it would reduce this list to a minimal failing case such as [0,1].
Checking type class laws
The same approach checks the laws of an instance you wrote. Here is a Monoid for a "max with a default" type, tested for associativity and identity:
newtype MaxInt = MaxInt Int deriving (Show, Eq)
instance Semigroup MaxInt where
MaxInt a <> MaxInt b = MaxInt (max a b)
instance Monoid MaxInt where
mempty = MaxInt minBound
-- a deliberately broken instance for comparison
newtype Avg = Avg Int deriving (Show, Eq)
instance Semigroup Avg where
Avg a <> Avg b = Avg ((a + b) `div` 2)
samples :: [Int]
samples = [-7, 0, 3, 12, 99, -100, 42]
triples :: [(Int, Int, Int)]
triples = [(a, b, c) | a <- samples, b <- samples, c <- samples]
assocHolds :: (Semigroup s, Eq s) => (Int -> s) -> Bool
assocHolds wrap = and [(x <> y) <> z == x <> (y <> z) | (a, b, c) <- triples, let (x, y, z) = (wrap a, wrap b, wrap c)]
firstAssocFailure :: (Int, Int, Int) -> Bool
firstAssocFailure (a, b, c) = (Avg a <> Avg b) <> Avg c /= Avg a <> (Avg b <> Avg c)
main :: IO ()
main = do
putStrLn ("MaxInt associative: " ++ show (assocHolds MaxInt))
putStrLn ("MaxInt identity: " ++ show (all (\a -> mempty <> MaxInt a == MaxInt a && MaxInt a <> mempty == MaxInt a) samples))
putStrLn ("Avg associative: " ++ show (assocHolds Avg))
print (take 1 (filter firstAssocFailure triples))MaxInt associative: True
MaxInt identity: True
Avg associative: False
[(-7,-7,0)]
Averaging pairwise is not associative. For the first failing triple, (Avg (-7) <> Avg (-7)) <> Avg 0 is Avg (-4), while Avg (-7) <> (Avg (-7) <> Avg 0) is Avg (-6). So Avg must not be made a Semigroup: code like mconcat or a parallel fold would give different answers depending on how the work is grouped.
Unit tests still have their place
Properties capture general rules; examples capture specific, known cases (including past bugs). A simple example-based test in plain Haskell looks like this:
import Control.Monad (unless)
assertEqual :: (Eq a, Show a) => String -> a -> a -> IO Bool
assertEqual label expected actual = do
let ok = expected == actual
unless ok $ putStrLn ("FAIL " ++ label ++ ": expected " ++ show expected ++ ", got " ++ show actual)
return ok
slugify :: String -> String
slugify = map (\c -> if c == ' ' then '-' else c) . filter (/= '!')
main :: IO ()
main = do
results <- sequence
[ assertEqual "spaces" "hello-world" (slugify "hello world")
, assertEqual "bang" "wow" (slugify "wow!")
, assertEqual "upper" "abc" (slugify "ABC")
]
putStrLn (show (length (filter id results)) ++ "/" ++ show (length results) ++ " tests passed")FAIL upper: expected "abc", got "ABC"
2/3 tests passed
Test frameworks such as hspec and tasty provide this structure (plus nice reports) and integrate QuickCheck properties next to unit tests.
Test yourself
What does property-based testing check?
- One example per function
- That a stated property holds for many generated inputs
- Only performance
- That code compiles
What does QuickCheck do after finding a failing input?
- Stops without output
- Shrinks it to a smaller counterexample
- Retries until it passes
- Deletes the test
Which law must every Semigroup instance satisfy?
- Commutativity:
a <> b == b <> a - Associativity:
(a <> b) <> c == a <> (b <> c) a <> a == aa <> b /= a