I need to generate a random number from 1 to 5 which isn’t already in the passed list.
Here is my code:
questionNumberGenerator:: [Int]->Int
questionNumberGenerator ql = do
g <- newStdGen
let qn=(fst((randomR (1, 5) g)))::Int
let element = (elem qn ql)::Bool
if(element==True)
then
questionNumberGenerator ql
else do
return qn
What am I doing wrong?
The problem is your type signature; it should be:
questionNumberGeneratorreturns an IO action (which it must, to use the global random number generator), but your type signature says it’s pure.If you want to use
questionNumberGeneratorin pure code, you’ll have to thread the random number generator state explicitly, like this:By the way,
(element==True)is redundant;elementmeans the exact same thing.