Search code examples
haskelltestingfunctional-programmingfunctional-testingquickcheck

create an arbitrary intance of "type"


I have the following,

type Pos = (Int, Int) 

I want to generate random values of this type with some restrictions (both has to be 0-8)

I would like to do something like

instance Arbitrary Pos where
  arbitrary = do x <- choose(0,8) 
                 y <- choose(0,8)
                 return (x,y) 

and then use it in my test to have valid positions.

This won't work bc I'm aliasing(?) tuples

other methods I have tried are to use implications in my test to say

prop_my_prop (x,y) = abs x < 9  && abs y < 9 ==> ...

but I think that's pretty ugly and in theory it might exhaust the quickchecktest (run over 1000 times).

this is an assignment so I just want some indication were to look or how to approach this, I'm not allowed to change Pos.


Solution

  • Don Stewart's answer describes the arguably best way to do it. However, if for some reason you don't want to use a newtype you can use a custom generator as follows:

    positionsToTest :: Gen Pos
    positionsToTest = do x <- choose (0,8)
                         y <- choose (0,8)
                         return (x,y)
    
    prop_myTest = forAll positionsToTest ( \ pos -> myProperty pos )
    

    Runnung quickCheck on prop_myTest should do what you want.