-1

I have been reading that the only way to generate random numbers in Haskell is using IO. However, when I want to use this random number with the (!!) operator I can't because it only takes in an Int and not IO Int.

Suppose I have a list [Monday, Tuesday, Wednesday, Thursday, Frdiay]. I want to randomly select an element from that list. I am not sure how to using randomRIO.

Thanks for any help.

sshine
  • 15,183
  • 1
  • 44
  • 63
  • You need to write `randomIndex – arrowd Dec 18 '20 at 03:36
  • 1
    You *must* perform random generation in the IO monad (or another random monad) as random generation is not pure. Also see [this answer](https://stackoverflow.com/a/58182586/12372506) for more detailed explanation. – CH. Dec 18 '20 at 06:19

1 Answers1

4
randomElement :: [a] -> IO a
randomElement list = do
  gen <- getStdGen
  let (i, _) = randomR (0, length list - 1) gen
  return $ list !! i
Vlad the Impala
  • 14,932
  • 15
  • 71
  • 118