简体   繁体   中英

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)

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM