[Haskell-beginners] Spec with QuickCheck generationg list of list of the same length

Ondrej Nekola ondra at nekola.cz
Sun Feb 15 20:53:32 UTC 2015


Thanks, it sent me to the (higly probably) right direction:

newtype RectList  = RectList [LVector] deriving Show

instance Arbitrary RectList  where
     arbitrary = do
         m <- getPositive <$> arbitrary
         n <- getPositive <$> arbitrary

         RectList <$> replicateM n (vector m)

and the test can look like this:

it "average times number is sum" $
             property (\(RectList x) -> null $ nozeroMembers $ zipWith 
(-) ( map (* (fromIntegral $ length x)) (average x)) (sumVect x) )

Thanks again
    Ondrej
> On 2015-02-15 at 10:52, Ondrej Nekola <ondra at nekola.cz> wrote:
>> How can I generate list of lists, where all the included lists are of
>> the same length?
> The general approach is to make a newtype, the Arbitrary instance of
> which does what you want.  For example, QucickCheck includes newtypes
> Positive[1] and NonNegative[2], that generate restricted numbers.
>
> For your case, I'd write something like (untested):
>
> ```
> newtype RectList a = RectList [[a]]
>
> instance Arbitrary a => Arbitrary RectList a where
>    arbitrary = do
>      -- length of inner lists
>      m <- getPositive <$> arbitrary
>      -- length of outer list, can be zero
>      n <- getNonNegative <$> arbitrary
>      RectList <$> replicateM n (vector m)
> ```
>
> vector here is another function provided by QuickCheck: [3].
>
> Hope this helps.
>
> bergey
>
>> Link for some tutorial *) can be, I believe, enough but I would be glad
>> for any help.
>>
>> Thanks
>>      Ondra @satai Nekola
>>      ondra at nekola.cz
>>
>> *) Maybe I have not trained my google good enough yet, but lack of
>> tutorials describing more than the most basic usecase is probably the
>> most problematic point in re-learning Haskell so far.
>> _______________________________________________
>> Beginners mailing list
>> Beginners at haskell.org
>> http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners
> Footnotes:
> [1]  http://hackage.haskell.org/package/QuickCheck-2.7.6/docs/Test-QuickCheck.html#t:Positive
>
> [2]  http://hackage.haskell.org/package/QuickCheck-2.7.6/docs/Test-QuickCheck.html#t:NonNegative
>
> [3]  http://hackage.haskell.org/package/QuickCheck-2.7.6/docs/Test-QuickCheck-Arbitrary.html#v:vector
>
>



More information about the Beginners mailing list