0

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,635
  • 1
  • 41
  • 66
  • You need to write `randomIndex <- getRandomR (0, 5)` somewhere in a do-block belonging to `IO` monad computation. Read up some general monad tutorial. – 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

3
randomElement :: [a] -> IO a
randomElement list = do
  gen <- getStdGen
  let (i, _) = randomR (0, length list - 1) gen
  return $ list !! i
Vlad the Impala
  • 15,572
  • 16
  • 81
  • 124