Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell Random from Datatype

Tags:

random

haskell

Im pretty new to Haskell. I have a datatype:

data Sentence= Prop Int
          | No Sentence
          | And [Sentence]
          | Or [Sentence]
          deriving Eq

I already wrote a Show instance for it

However, whether it makes sense or not, I would like to be able to generate a random Sentence. How can i accomplish this in Haskell?

like image 467
Len Avatar asked Sep 22 '10 12:09

Len


1 Answers

Random number generation is a typical example of an "impure" operation, since calling a random generator twice will of course yield different results - Haskell's nature disallows this.

Therefore, you need to use a so called monad Gen a that represents a random generator, that, when run, yields a value of type a.

Fortunately, you can combine these generators in a quite nice syntax ...

So, you just need some library that implements such a generator - and here we go.

randomNo   = No <$> randomSentence
randomProp = Prop <$> choose (1, 10) 
[...]

randomSentence = oneOf [randomNo, randomProp, ...]
like image 98
Dario Avatar answered Sep 19 '22 04:09

Dario