1

I want to generate random number in Haskell and to use this number for concatenation with my text. I found this function but it doesn't give me char type. How can I change this function?

rollDice :: IO Int 
rollDice = getStdRandom (randomR (1,3))

1 Answers1

1

randomR :: (Random a, RandomGen g) => (a, a) -> g -> (a, g) can generate random items for any type that is an instance of the Random typeclass, hence for a Char, you can work with:

rollDice :: IO Char
rollDice = getStdRandom (randomR ('a', 'z'))

or for any value of Char:

rollDice :: IO Char
rollDice = getStdRandom random
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
  • Can I get type [Char] instead of usual Char? –  Apr 01 '22 at 09:56
  • @HandcraftingCountry: with `getStdRandom randoms` – Willem Van Onsem Apr 01 '22 at 10:02
  • ``` rollDice :: IO [Char] rollDice = getStdRandom (randoms ("1","3")) ``` Like this? –  Apr 01 '22 at 10:14
  • @HandcraftingCountry: no `getStdRandom (randomRs ('1','3'))`, but here it probably makes more sense to generate an `IO [Int]`, so `getStdRandom (randomRs (1,3))` – Willem Van Onsem Apr 01 '22 at 10:15
  • What if I want to use it us type [Char] in another function, but it's type (IO [Char]). How can I delete this IO from type? (sorry for stupid questions) –  Apr 01 '22 at 10:31
  • @HandcraftingCountry: you don't: that's the entire point of `IO` to protect against impurity https://stackoverflow.com/q/36729022/67579 – Willem Van Onsem Apr 01 '22 at 10:34