Search code examples
haskellquickcheck

Generate choose on custom data type with 2 options


I am trying to achieve something very simple. I have this data type :

import Test.QuickCheck
import System.Random
data Letter = G | B deriving(Show, Eq, Bounded)

arbitraryLetter :: Gen Letter
arbitraryLetter = choose (G,B)

I am compiling and getting this error

    • No instance for (Random Letter) arising from a use of ‘choose’
    • In the expression: choose (G, B)
      In an equation for ‘arbitraryLetter’:
      arbitraryLetter = choose (G, B)

Why isn't this working? I want to be able to use QuickCheck on this data type.


Solution

  • choose has type Random a => (a, a) -> Gen a, so choose (G, B) requires a Random instance for your Letter type. If you want to create a generator from a set of values you can use elements instead:

    arbitraryLetter :: Gen Letter
    arbitraryLetter = elements [G, B]