首页 > 解决方案 > Combining generator for different datatypes in Quickcheck

问题描述

I would like to combine two custom generators of different data type, but which are grouped together in another datatype.

In the following example, I would like to use the generator for Legumes and AnimalProteins to create another one for Proteins. choose and elements does not work as the type are different. Casting the generators as gen Proteins does not work either.

data AnimalProteins = Beef | Chicken | Fish
data Legumes = WhiteBeans | RedBeans | Lentils | Chickpeas

data Proteins = AnimalProteins | Legumes deriving (Show)

rAnimalProteins :: Gen AnimalProteins
rAnimalProteins = elements [Beef , Chicken , Fish]

rLegumes :: Gen Legumes
rLegumes = elements [WhiteBeans , RedBeans , Lentils , Chickpeas]

-- This does not work !
rProteins :: Gen Proteins
rProteins = choose (rLegumes, rAnimalProteins)

The solution may be simple but I'm quite stuck here as a beginner. Thanks !

标签: haskellquickcheck

解决方案


The problem is that your Proteins data type doesn't actually contain any AnimalProteins or Legumes! Yes, you've named the constructors of Proteins the same way, but constructors live in the term language, not in the type language, so the compiler doesn't automatically associate them to the AnimalProteins type.

To do that, you need to be explicit:

data Proteins = AnimalProteins AnimalProteins | Legumes Legumes

推荐阅读