[Haskell-cafe] A Random Question

Benja Fallenstein benja.fallenstein at gmail.com
Sat Dec 15 05:34:20 EST 2007


Hi Dominic,

On Dec 15, 2007 10:38 AM, Dominic Steinitz
<dominic.steinitz at blueyonder.co.uk> wrote:
> > Supply.hs:33:13:
> >     Couldn't match expected type `g' against inferred type `MyGen'
> >       `g' is a rigid type variable bound by
> >           the type signature for `randomR' at <no location info>
> >       Expected type: (Foo, Foo) -> g -> (Foo, g)
> >       Inferred type: (Foo, Foo) -> MyGen -> (Foo, MyGen)
> >     In the expression: myRandomR
> >     In the definition of `randomR': randomR = myRandomR
> > Failed, modules loaded: none.
>
> I have two questions:
>
> 1. Why can't I instantiate a type class with any function I like
> provided it fits the type signature?

The problem here is that myRandomR does not match the type signature
in the class. You have

myRandomR :: (Foo, Foo) -> MyGen -> (Foo, MyGen)

but you need

randomR :: RandomGen g => (Foo, Foo) -> g -> (Foo, g)

i.e., the function is required to be more generic than the one you provide.

The good news is that you don't need to declare Foo at all. You only
need to declare an instance of Random if you want to generate random
*values* of some new type. If you just want numbers, remove all the
stuff about Foo and call (for example)

randomR (0,5) $ MyGen 18

and it'll give you a number and a new MyGen.

> 2. Is this the right approach to generating predictable arbitrary
> values? Are there others?

Seems entirely fine to me.

Hope this helps,
- Benja


More information about the Haskell-Cafe mailing list