Search code examples
haskellfunctional-programminggeneratorquickcheck

Creating generators from user defined data types in haskell


I need some suggestions on how I can go about creating a random generator for the Foo data type such that the list of Boo is never empty?

data Boo = Boo Float Float Float
data Foo = Foo Float Float Float [Boo]

Solution

  • You can use the listOf1 function to get a generator which generates non-empty lists and use that for defining an appropriate Arbitrary instance, like:

    import Test.QuickCheck
    import Control.Applicative
    
    instance Arbitrary Boo
    
    instance Arbitrary Foo where
      arbitrary = Foo <$> arbitrary <*> arbitrary <*> arbitrary <*> listOf1 arbitrary