zzu
zzu

Reputation: 268

Haskell: Get one of alternative type

Say I have a type such as:

data Cell = Empty | Full

Does Haskell provide a simple way to nondeterministically call one or the other of these constructors? Basically I am trying to randomize which constructor gets called, e.g. [CellOfSomeType | i <- [1..somerange]]

Upvotes: 0

Views: 131

Answers (1)

Thomas M. DuBuisson
Thomas M. DuBuisson

Reputation: 64750

Just get a random bit and set the value to Full or Empty based on that bit. For example:

import System.Random

You seem to be talking about System.Random, but this sort of information should be included in the question.

data Cell = Full | Empty
          deriving (Eq,Ord,Show,Enum)

I derived Enum for use with ranged randoms. Now we are going to define an instance for the Random class so you can use a couple of the common libraries to generate random values of type Cell. The Random class requires we at least define random and randomR methods.

instance Random Cell where
  random g = let (a,g') = random g
                 val = if a then Full else Empty
             in (val,g')
  randomR (l,h) g = let (a,g') = randomR (fromEnum l, fromEnum h) g
                    in (toEnum a, g')

Since your type is identical to Bool we can just generate a random bool (a bit) and select one of your two constructors. The ranged randoms are a little more of a nuisance but we just generate an Int somewhere between the lower bound and upper bounds requested then acquire the constructor matching that Int value.

Upvotes: 3

Related Questions