I'm trying to use HSpec and QuickCheck to verify properties of Monoids (associativity and identity element). I am going to verify particular instances, but would like to keep most of the code polymorphic. This is what I came up with after several hours:
module Test where
import Test.Hspec
import Test.QuickCheck
import Data.Monoid
instance (Arbitrary a) => Arbitrary (Sum a) where
arbitrary = fmap Sum arbitrary
instance (Arbitrary a) => Arbitrary (Product a) where
arbitrary = fmap Product arbitrary
prop_Monoid_mappend_mempty_x x = mappend mempty x === x
sumMonoidSpec = it "mappend mempty x = x" $ property (prop_Monoid_mappend_mempty_x :: Sum Int -> Property)
productMonoidSpec = it "mappend mempty x = x" $ property (prop_Monoid_mappend_mempty_x :: Product Double -> Property)
main :: IO ()
main = hspec $ do
describe "Data.Monoid.Sum" $ do
sumMonoidSpec
describe "Data.Monoid.Product" $ do
productMonoidSpec
What I would like to have though is polymorphic
monoidSpec = it "mappend mempty x = x" $ property prop_Monoid_mappend_mempty_x
and specify the actual Monoid instance (Sum, Product) and the type (Int, Double) later on. The issue is it wouldn't type check. I keep getting
src/Test.hs@18:42-18:50 No instance for (Arbitrary a0) arising from a use of property
The type variable a0 is ambiguous
Note: there are several potential instances:
instance Arbitrary a => Arbitrary (Product a)
-- Defined at /home/app/isolation-runner-work/projects/68426/session.207/src/src/Test.hs:10:10
instance Arbitrary a => Arbitrary (Sum a)
-- Defined at /home/app/isolation-runner-work/projects/68426/session.207/src/src/Test.hs:7:10
instance Arbitrary () -- Defined in Test.QuickCheck.Arbitrary
...plus 27 others …
src/Test.hs@18:51-18:79 No instance for (Monoid a0)
arising from a use of prop_Monoid_mappend_mempty_x
The type variable a0 is ambiguous
Note: there are several potential instances:
instance Monoid () -- Defined in Data.Monoid
instance (Monoid a, Monoid b) => Monoid (a, b)
-- Defined in Data.Monoid
instance (Monoid a, Monoid b, Monoid c) => Monoid (a, b, c)
-- Defined in Data.Monoid
...plus 18 others …
I know I need to constraint Monoid in polymorphic version to be Arbitrary, Eq and Show but I don't know how.
The question is how to express specs for Monoid in a polymorphic way and avoid code duplication?