Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell: How to use random integer from randomRIO in a function that returns a boolean

Tags:

random

haskell

I am new to Haskell and i'm having a problem with using the IO Int from randomRIO function. My goal is to get a random Int value, say r, and to return True if r < x or false otherwise, but i don't know how to do it.

my function should look like:

randomCompare :: Int->Bool

randomCompare x

  | x < r = True -- somehow i want to r <- randomRIO(start,end) 

  | otherwise = False                

I know there is a designed intention with keeping IO vals in context for purity etc.. but i don't see why using a random number for a Boolean function should be "bad".

Thanks.

like image 950
Noob Saibot Avatar asked Apr 15 '26 12:04

Noob Saibot


1 Answers

import System.Random(randomIO)

randomCompare :: Int -> IO Bool
randomCompare x = do
  r <- randomIO
  return $ x < r

IO is neither good nor bad, it just declares that your function has side effects. Here the side effect is modifying the state of the global random number generator, so that a subsequent call to randomIO will give another number (it wouldn't be random if it was constant !).

IO does force all calling functions to be IO too (the ones that want to use the IO Bool). However, if a calling function is IO only by consuming this IO Bool, if it has no other side effects, then you can separate it as a pure function f :: Bool -> SomeType and functorially apply it on the IO, ie

f <$> randomCompare i

So the IO monad only costs you to replace the ordinary function call $ by the functorial fmap, also noted <$>. Is it so much longer to type ?

If you absolutely want to leave the IO monad (why ?), you can also draw all the random values you need first, store them in a list, then apply pure functions on that list.

like image 172
V. Semeria Avatar answered Apr 18 '26 08:04

V. Semeria



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!