-3

I need to make an instance of arbitrary on my Haskell program, I'm creating a deck of cards (which is of type deck), and deck is a list of Cards, in order to make a new deck the program uses a mkStdGen and a number to prompt a seed, in order to randomize the new deck.

This deck needs to have an instance of arbitrary to pass the QuickTest property tests.

Here's some code

 data Carta = C (Valor,Naipe) deriving (Eq,Ord)

 instance Show Carta where
 show (C (v,n)) =show v ++ show n

 data Baralho = B [Carta] 

  instance Show Baralho where
  show (B []) = ""
  show (B [c]) = show c
  show (B (c:cs)) = show c ++ "," ++ show (B cs)

  type Mao = [Carta]

  baralho40 :: Baralho

  baralho40 = B [C (x,y)|y<-[Paus .. Espadas],x<-[As .. Rei]]

  baralhar :: StdGen -> Baralho -> Baralho

  baralhar g (B baralho) = B $ map snd $ sort $ zip (randomRs (1,(length       baralho)^3) g) baralho
duplode
  • 33,731
  • 7
  • 79
  • 150

1 Answers1

1

A very basic instance for Carta could be:

instance Arbitrary Carta where
  arbitrary = Carta <$> vn
    where
      vn = (,) <$> v <*> n
      v  = elements [Paus .. Espadas]
      n  = elements [As .. Rei]

The elements function from module Test.QuickCheck takes a list of values and returns a generator for those values (i.e. something to select one of those values at random):

elements :: [a] -> Gen a

The instance above uses this to independently generate a random Valor and a random Naipe for a card. Those to values are then combined to a tuple (vn is a generator for a tuple, type Gen (Valor,Naipe)). After that wrap this to a generator for the Carta itself.

To generate a random deck of cards (where you don't want to have duplicates), have a look at the function:

shuffle :: [a] -> Gen [a]

in Test.QuickCheck. It generates random permutations of a list of items. It will also be helpful to make Carta, Valor and Naipe elements of Enum.

mschmidt
  • 2,740
  • 4
  • 17
  • 31