Search code examples
genericshaskellfunctional-programmingsignaturepurely-functional

Haskell: How to do a generic random function?


I am trying to make a generic function that returns a random value. I can make one working for floats, followed by another one working for ints... like this:

randomFloat :: StdGen -> Float-> Float-> (Float, StdGen)
randomFloat rndGen min max = randomR (min, max) rndGen :: (Float, StdGen)

randomInt :: StdGen -> Int-> Int-> (Int, StdGen)
randomInt rndGen min max = randomR (min, max) rndGen :: (Int, StdGen)

but I'd like to have one working for any relevant variable type. How can I do it? So far, I have this but this won't work:

randomNbr :: (Random a) => StdGen -> a -> a -> (a, StdGen)
randomNbr rndGen min max = randomR (min, max) rndGen :: (a, StdGen)

Solution

  • The a in your :: (a, StdGen) doesn't refer to the same a as in your function's type signature. Just remove :: (a, StdGen) and it will work.

    More generally, if you want/need to use a type variable in an annotation in an expression like that, you need to enable GHC's ScopedTypeVariables extension.